var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x2)(function(x2) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x2 + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
  try {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  } catch (e) {
    throw mod = 0, e;
  }
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], 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
));

// node_modules/oregondsp/kotlin/kotlin-kotlin-stdlib-js-ir.js
var require_kotlin_kotlin_stdlib_js_ir = __commonJS({
  "node_modules/oregondsp/kotlin/kotlin-kotlin-stdlib-js-ir.js"(exports, module) {
    if (typeof ArrayBuffer.isView === "undefined") {
      ArrayBuffer.isView = function(a) {
        return a != null && a.__proto__ != null && a.__proto__.__proto__ === Int8Array.prototype.__proto__;
      };
    }
    if (typeof Math.clz32 === "undefined") {
      Math.clz32 = /* @__PURE__ */ (function(log3, LN2) {
        return function(x2) {
          var asUint = x2 >>> 0;
          if (asUint === 0) {
            return 32;
          }
          return 31 - (log3(asUint) / LN2 | 0) | 0;
        };
      })(Math.log, Math.LN2);
    }
    (function() {
      if (typeof globalThis === "object")
        return;
      Object.defineProperty(Object.prototype, "__magic__", { get: function() {
        return this;
      }, configurable: true });
      __magic__.globalThis = __magic__;
      delete Object.prototype.__magic__;
    })();
    if (typeof Math.imul === "undefined") {
      Math.imul = function imul(a, b) {
        return (a & 4294901760) * (b & 65535) + (a & 65535) * (b | 0) | 0;
      };
    }
    (function(root2, factory) {
      if (typeof define === "function" && define.amd)
        define(["exports"], factory);
      else if (typeof exports === "object")
        factory(module.exports);
      else
        root2["kotlin-kotlin-stdlib-js-ir"] = factory(typeof this["kotlin-kotlin-stdlib-js-ir"] === "undefined" ? {} : this["kotlin-kotlin-stdlib-js-ir"]);
    })(exports, function(_) {
      "use strict";
      var imul = Math.imul;
      var clz32 = Math.clz32;
      var isView = ArrayBuffer.isView;
      Exception.prototype = Object.create(Error.prototype);
      Exception.prototype.constructor = Exception;
      RuntimeException.prototype = Object.create(Exception.prototype);
      RuntimeException.prototype.constructor = RuntimeException;
      KotlinNothingValueException.prototype = Object.create(RuntimeException.prototype);
      KotlinNothingValueException.prototype.constructor = KotlinNothingValueException;
      Level.prototype = Object.create(Enum.prototype);
      Level.prototype.constructor = Level;
      AbstractList.prototype = Object.create(AbstractCollection.prototype);
      AbstractList.prototype.constructor = AbstractList;
      SubList.prototype = Object.create(AbstractList.prototype);
      SubList.prototype.constructor = SubList;
      ListIteratorImpl.prototype = Object.create(IteratorImpl.prototype);
      ListIteratorImpl.prototype.constructor = ListIteratorImpl;
      function callsInPlace$default(lambda, kind, $mask0, $handler) {
        if (!(($mask0 & 2) === 0))
          kind = InvocationKind_UNKNOWN_getInstance();
        return $handler == null ? this.callsInPlace_jmp6z0_k$(lambda, kind) : $handler(lambda, kind);
      }
      InvocationKind.prototype = Object.create(Enum.prototype);
      InvocationKind.prototype.constructor = InvocationKind;
      function plus(context) {
        var tmp;
        if (context === EmptyCoroutineContext_getInstance()) {
          tmp = this;
        } else {
          tmp = context.fold_6dbyow_k$(this, CoroutineContext$plus$lambda);
        }
        return tmp;
      }
      function get3(key) {
        var tmp;
        if (equals(this.get_key_18j28a_k$(), key)) {
          tmp = isInterface(this, Element2) ? this : THROW_CCE();
        } else {
          tmp = null;
        }
        return tmp;
      }
      function fold(initial, operation) {
        return operation(initial, this);
      }
      function minusKey(key) {
        return equals(this.get_key_18j28a_k$(), key) ? EmptyCoroutineContext_getInstance() : this;
      }
      function releaseInterceptedContinuation(continuation) {
      }
      function get_0(key) {
        if (key instanceof AbstractCoroutineContextKey) {
          var tmp;
          if (key.isSubKey_5an70z_k$(this.get_key_18j28a_k$())) {
            var tmp_0 = key.tryCast_hqzvw1_k$(this);
            tmp = (!(tmp_0 == null) ? isInterface(tmp_0, Element2) : false) ? tmp_0 : null;
          } else {
            tmp = null;
          }
          return tmp;
        }
        var tmp_1;
        if (Key_getInstance() === key) {
          tmp_1 = isInterface(this, Element2) ? this : THROW_CCE();
        } else {
          tmp_1 = null;
        }
        return tmp_1;
      }
      function minusKey_0(key) {
        if (key instanceof AbstractCoroutineContextKey) {
          return (key.isSubKey_5an70z_k$(this.get_key_18j28a_k$()) ? !(key.tryCast_hqzvw1_k$(this) == null) : false) ? EmptyCoroutineContext_getInstance() : this;
        }
        return Key_getInstance() === key ? EmptyCoroutineContext_getInstance() : this;
      }
      CoroutineSingletons.prototype = Object.create(Enum.prototype);
      CoroutineSingletons.prototype.constructor = CoroutineSingletons;
      Default.prototype = Object.create(Random.prototype);
      Default.prototype.constructor = Default;
      XorWowRandom.prototype = Object.create(Random.prototype);
      XorWowRandom.prototype.constructor = XorWowRandom;
      function contains(value) {
        return compareTo_0(value, this.get_start_iypx6h_k$()) >= 0 ? compareTo_0(value, this.get_endInclusive_r07xpi_k$()) <= 0 : false;
      }
      function isEmpty() {
        return compareTo_0(this.get_start_iypx6h_k$(), this.get_endInclusive_r07xpi_k$()) > 0;
      }
      function contains_0(value) {
        return compareTo_0(value, this.get_start_iypx6h_k$()) >= 0 ? compareTo_0(value, this.get_endExclusive_pmwm6k_k$()) < 0 : false;
      }
      function isEmpty_0() {
        return compareTo_0(this.get_start_iypx6h_k$(), this.get_endExclusive_pmwm6k_k$()) >= 0;
      }
      IntRange.prototype = Object.create(IntProgression.prototype);
      IntRange.prototype.constructor = IntRange;
      CharRange.prototype = Object.create(CharProgression.prototype);
      CharRange.prototype.constructor = CharRange;
      LongRange.prototype = Object.create(LongProgression.prototype);
      LongRange.prototype.constructor = LongRange;
      IntProgressionIterator.prototype = Object.create(IntIterator.prototype);
      IntProgressionIterator.prototype.constructor = IntProgressionIterator;
      CharProgressionIterator.prototype = Object.create(CharIterator.prototype);
      CharProgressionIterator.prototype.constructor = CharProgressionIterator;
      LongProgressionIterator.prototype = Object.create(LongIterator.prototype);
      LongProgressionIterator.prototype.constructor = LongProgressionIterator;
      KVariance.prototype = Object.create(Enum.prototype);
      KVariance.prototype.constructor = KVariance;
      Error_0.prototype = Object.create(Error.prototype);
      Error_0.prototype.constructor = Error_0;
      NotImplementedError.prototype = Object.create(Error_0.prototype);
      NotImplementedError.prototype.constructor = NotImplementedError;
      UIntRange.prototype = Object.create(UIntProgression.prototype);
      UIntRange.prototype.constructor = UIntRange;
      ULongRange.prototype = Object.create(ULongProgression.prototype);
      ULongRange.prototype.constructor = ULongRange;
      DeprecationLevel.prototype = Object.create(Enum.prototype);
      DeprecationLevel.prototype.constructor = DeprecationLevel;
      AnnotationTarget.prototype = Object.create(Enum.prototype);
      AnnotationTarget.prototype.constructor = AnnotationTarget;
      AnnotationRetention.prototype = Object.create(Enum.prototype);
      AnnotationRetention.prototype.constructor = AnnotationRetention;
      AbstractMutableCollection.prototype = Object.create(AbstractCollection.prototype);
      AbstractMutableCollection.prototype.constructor = AbstractMutableCollection;
      ListIteratorImpl_0.prototype = Object.create(IteratorImpl_0.prototype);
      ListIteratorImpl_0.prototype.constructor = ListIteratorImpl_0;
      AbstractMutableList.prototype = Object.create(AbstractMutableCollection.prototype);
      AbstractMutableList.prototype.constructor = AbstractMutableList;
      SubList_0.prototype = Object.create(AbstractMutableList.prototype);
      SubList_0.prototype.constructor = SubList_0;
      ArrayList.prototype = Object.create(AbstractMutableList.prototype);
      ArrayList.prototype.constructor = ArrayList;
      NodeJsOutput.prototype = Object.create(BaseOutput.prototype);
      NodeJsOutput.prototype.constructor = NodeJsOutput;
      BufferedOutput.prototype = Object.create(BaseOutput.prototype);
      BufferedOutput.prototype.constructor = BufferedOutput;
      BufferedOutputToConsoleLog.prototype = Object.create(BufferedOutput.prototype);
      BufferedOutputToConsoleLog.prototype.constructor = BufferedOutputToConsoleLog;
      PrimitiveKClassImpl.prototype = Object.create(KClassImpl.prototype);
      PrimitiveKClassImpl.prototype.constructor = PrimitiveKClassImpl;
      NothingKClassImpl.prototype = Object.create(KClassImpl.prototype);
      NothingKClassImpl.prototype.constructor = NothingKClassImpl;
      SimpleKClassImpl.prototype = Object.create(KClassImpl.prototype);
      SimpleKClassImpl.prototype.constructor = SimpleKClassImpl;
      booleanArrayIterator$1.prototype = Object.create(BooleanIterator.prototype);
      booleanArrayIterator$1.prototype.constructor = booleanArrayIterator$1;
      charArrayIterator$1.prototype = Object.create(CharIterator.prototype);
      charArrayIterator$1.prototype.constructor = charArrayIterator$1;
      byteArrayIterator$1.prototype = Object.create(ByteIterator.prototype);
      byteArrayIterator$1.prototype.constructor = byteArrayIterator$1;
      shortArrayIterator$1.prototype = Object.create(ShortIterator.prototype);
      shortArrayIterator$1.prototype.constructor = shortArrayIterator$1;
      intArrayIterator$1.prototype = Object.create(IntIterator.prototype);
      intArrayIterator$1.prototype.constructor = intArrayIterator$1;
      floatArrayIterator$1.prototype = Object.create(FloatIterator.prototype);
      floatArrayIterator$1.prototype.constructor = floatArrayIterator$1;
      longArrayIterator$1.prototype = Object.create(LongIterator.prototype);
      longArrayIterator$1.prototype.constructor = longArrayIterator$1;
      doubleArrayIterator$1.prototype = Object.create(DoubleIterator.prototype);
      doubleArrayIterator$1.prototype.constructor = doubleArrayIterator$1;
      Long.prototype = Object.create(Number_0.prototype);
      Long.prototype.constructor = Long;
      IrLinkageError.prototype = Object.create(Error_0.prototype);
      IrLinkageError.prototype.constructor = IrLinkageError;
      IllegalArgumentException.prototype = Object.create(RuntimeException.prototype);
      IllegalArgumentException.prototype.constructor = IllegalArgumentException;
      IllegalStateException.prototype = Object.create(RuntimeException.prototype);
      IllegalStateException.prototype.constructor = IllegalStateException;
      NoSuchElementException.prototype = Object.create(RuntimeException.prototype);
      NoSuchElementException.prototype.constructor = NoSuchElementException;
      UnsupportedOperationException.prototype = Object.create(RuntimeException.prototype);
      UnsupportedOperationException.prototype.constructor = UnsupportedOperationException;
      IndexOutOfBoundsException.prototype = Object.create(RuntimeException.prototype);
      IndexOutOfBoundsException.prototype.constructor = IndexOutOfBoundsException;
      NullPointerException.prototype = Object.create(RuntimeException.prototype);
      NullPointerException.prototype.constructor = NullPointerException;
      NoWhenBranchMatchedException.prototype = Object.create(RuntimeException.prototype);
      NoWhenBranchMatchedException.prototype.constructor = NoWhenBranchMatchedException;
      ClassCastException.prototype = Object.create(RuntimeException.prototype);
      ClassCastException.prototype.constructor = ClassCastException;
      UninitializedPropertyAccessException.prototype = Object.create(RuntimeException.prototype);
      UninitializedPropertyAccessException.prototype.constructor = UninitializedPropertyAccessException;
      function fold_0(_this__u8e3s4, initial, operation) {
        var accumulator = initial;
        var indexedObject = _this__u8e3s4;
        var inductionVariable = 0;
        var last = indexedObject.length;
        while (inductionVariable < last) {
          var element = indexedObject[inductionVariable];
          inductionVariable = inductionVariable + 1 | 0;
          accumulator = operation(accumulator, element);
        }
        return accumulator;
      }
      function get_indices(_this__u8e3s4) {
        return new IntRange(0, get_lastIndex(_this__u8e3s4));
      }
      function get_indices_0(_this__u8e3s4) {
        return new IntRange(0, get_lastIndex_0(_this__u8e3s4));
      }
      function get_lastIndex(_this__u8e3s4) {
        return _this__u8e3s4.length - 1 | 0;
      }
      function get_lastIndex_0(_this__u8e3s4) {
        return _this__u8e3s4.length - 1 | 0;
      }
      function get_indices_1(_this__u8e3s4) {
        return new IntRange(0, get_lastIndex_1(_this__u8e3s4));
      }
      function indexOf(_this__u8e3s4, element) {
        if (element == null) {
          var inductionVariable = 0;
          var last = _this__u8e3s4.length - 1 | 0;
          if (inductionVariable <= last)
            do {
              var index = inductionVariable;
              inductionVariable = inductionVariable + 1 | 0;
              if (_this__u8e3s4[index] == null) {
                return index;
              }
            } while (inductionVariable <= last);
        } else {
          var inductionVariable_0 = 0;
          var last_0 = _this__u8e3s4.length - 1 | 0;
          if (inductionVariable_0 <= last_0)
            do {
              var index_0 = inductionVariable_0;
              inductionVariable_0 = inductionVariable_0 + 1 | 0;
              if (equals(element, _this__u8e3s4[index_0])) {
                return index_0;
              }
            } while (inductionVariable_0 <= last_0);
        }
        return -1;
      }
      function lastIndexOf(_this__u8e3s4, element) {
        if (element == null) {
          var inductionVariable = _this__u8e3s4.length - 1 | 0;
          if (0 <= inductionVariable)
            do {
              var index = inductionVariable;
              inductionVariable = inductionVariable + -1 | 0;
              if (_this__u8e3s4[index] == null) {
                return index;
              }
            } while (0 <= inductionVariable);
        } else {
          var inductionVariable_0 = _this__u8e3s4.length - 1 | 0;
          if (0 <= inductionVariable_0)
            do {
              var index_0 = inductionVariable_0;
              inductionVariable_0 = inductionVariable_0 + -1 | 0;
              if (equals(element, _this__u8e3s4[index_0])) {
                return index_0;
              }
            } while (0 <= inductionVariable_0);
        }
        return -1;
      }
      function get_lastIndex_1(_this__u8e3s4) {
        return _this__u8e3s4.length - 1 | 0;
      }
      function joinToString(_this__u8e3s4, separator, prefix, postfix, limit, truncated, transform2) {
        return joinTo(_this__u8e3s4, StringBuilder_init_$Create$_1(), separator, prefix, postfix, limit, truncated, transform2).toString();
      }
      function joinToString$default(_this__u8e3s4, separator, prefix, postfix, limit, truncated, transform2, $mask0, $handler) {
        if (!(($mask0 & 1) === 0))
          separator = ", ";
        if (!(($mask0 & 2) === 0))
          prefix = "";
        if (!(($mask0 & 4) === 0))
          postfix = "";
        if (!(($mask0 & 8) === 0))
          limit = -1;
        if (!(($mask0 & 16) === 0))
          truncated = "...";
        if (!(($mask0 & 32) === 0))
          transform2 = null;
        return joinToString(_this__u8e3s4, separator, prefix, postfix, limit, truncated, transform2);
      }
      function joinTo(_this__u8e3s4, buffer, separator, prefix, postfix, limit, truncated, transform2) {
        buffer.append_oz4qxs_k$(prefix);
        var count = 0;
        var indexedObject = _this__u8e3s4;
        var inductionVariable = 0;
        var last = indexedObject.length;
        $l$loop: while (inductionVariable < last) {
          var element = indexedObject[inductionVariable];
          inductionVariable = inductionVariable + 1 | 0;
          count = count + 1 | 0;
          if (count > 1) {
            buffer.append_oz4qxs_k$(separator);
          }
          if (limit < 0 ? true : count <= limit) {
            appendElement(buffer, element, transform2);
          } else
            break $l$loop;
        }
        if (limit >= 0 ? count > limit : false) {
          buffer.append_oz4qxs_k$(truncated);
        }
        buffer.append_oz4qxs_k$(postfix);
        return buffer;
      }
      function joinTo$default(_this__u8e3s4, buffer, separator, prefix, postfix, limit, truncated, transform2, $mask0, $handler) {
        if (!(($mask0 & 2) === 0))
          separator = ", ";
        if (!(($mask0 & 4) === 0))
          prefix = "";
        if (!(($mask0 & 8) === 0))
          postfix = "";
        if (!(($mask0 & 16) === 0))
          limit = -1;
        if (!(($mask0 & 32) === 0))
          truncated = "...";
        if (!(($mask0 & 64) === 0))
          transform2 = null;
        return joinTo(_this__u8e3s4, buffer, separator, prefix, postfix, limit, truncated, transform2);
      }
      function contains_1(_this__u8e3s4, element) {
        return indexOf_0(_this__u8e3s4, element) >= 0;
      }
      function indexOf_0(_this__u8e3s4, element) {
        var inductionVariable = 0;
        var last = _this__u8e3s4.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            if (element === _this__u8e3s4[index]) {
              return index;
            }
          } while (inductionVariable <= last);
        return -1;
      }
      function get_indices_2(_this__u8e3s4) {
        return new IntRange(0, get_lastIndex_2(_this__u8e3s4));
      }
      function get_lastIndex_2(_this__u8e3s4) {
        return _this__u8e3s4.length - 1 | 0;
      }
      function contains_2(_this__u8e3s4, element) {
        return indexOf_1(_this__u8e3s4, element) >= 0;
      }
      function indexOf_1(_this__u8e3s4, element) {
        var inductionVariable = 0;
        var last = _this__u8e3s4.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            if (element === _this__u8e3s4[index]) {
              return index;
            }
          } while (inductionVariable <= last);
        return -1;
      }
      function get_indices_3(_this__u8e3s4) {
        return new IntRange(0, get_lastIndex_3(_this__u8e3s4));
      }
      function get_lastIndex_3(_this__u8e3s4) {
        return _this__u8e3s4.length - 1 | 0;
      }
      function contains_3(_this__u8e3s4, element) {
        return indexOf_2(_this__u8e3s4, element) >= 0;
      }
      function indexOf_2(_this__u8e3s4, element) {
        var inductionVariable = 0;
        var last = _this__u8e3s4.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            if (element === _this__u8e3s4[index]) {
              return index;
            }
          } while (inductionVariable <= last);
        return -1;
      }
      function get_indices_4(_this__u8e3s4) {
        return new IntRange(0, get_lastIndex_4(_this__u8e3s4));
      }
      function get_lastIndex_4(_this__u8e3s4) {
        return _this__u8e3s4.length - 1 | 0;
      }
      function contains_4(_this__u8e3s4, element) {
        return indexOf_3(_this__u8e3s4, element) >= 0;
      }
      function indexOf_3(_this__u8e3s4, element) {
        var inductionVariable = 0;
        var last = _this__u8e3s4.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            if (element.equals(_this__u8e3s4[index])) {
              return index;
            }
          } while (inductionVariable <= last);
        return -1;
      }
      function get_indices_5(_this__u8e3s4) {
        return new IntRange(0, get_lastIndex_5(_this__u8e3s4));
      }
      function get_lastIndex_5(_this__u8e3s4) {
        return _this__u8e3s4.length - 1 | 0;
      }
      function indexOfFirst(_this__u8e3s4, predicate) {
        var index = 0;
        var tmp0_iterator = _this__u8e3s4.iterator_jk1svi_k$();
        while (tmp0_iterator.hasNext_bitz1p_k$()) {
          var item = tmp0_iterator.next_20eer_k$();
          if (predicate(item))
            return index;
          var tmp1 = index;
          index = tmp1 + 1 | 0;
        }
        return -1;
      }
      function indexOfLast(_this__u8e3s4, predicate) {
        var iterator = _this__u8e3s4.listIterator_5hanv9_k$(_this__u8e3s4.get_size_woubt6_k$());
        while (iterator.hasPrevious_qh0629_k$()) {
          if (predicate(iterator.previous_l2dfd5_k$())) {
            return iterator.nextIndex_jshxun_k$();
          }
        }
        return -1;
      }
      function any2(_this__u8e3s4, predicate) {
        var tmp;
        if (isInterface(_this__u8e3s4, Collection)) {
          tmp = _this__u8e3s4.isEmpty_y1axqb_k$();
        } else {
          tmp = false;
        }
        if (tmp)
          return false;
        var tmp0_iterator = _this__u8e3s4.iterator_jk1svi_k$();
        while (tmp0_iterator.hasNext_bitz1p_k$()) {
          var element = tmp0_iterator.next_20eer_k$();
          if (predicate(element))
            return true;
        }
        return false;
      }
      function all(_this__u8e3s4, predicate) {
        var tmp;
        if (isInterface(_this__u8e3s4, Collection)) {
          tmp = _this__u8e3s4.isEmpty_y1axqb_k$();
        } else {
          tmp = false;
        }
        if (tmp)
          return true;
        var tmp0_iterator = _this__u8e3s4.iterator_jk1svi_k$();
        while (tmp0_iterator.hasNext_bitz1p_k$()) {
          var element = tmp0_iterator.next_20eer_k$();
          if (!predicate(element))
            return false;
        }
        return true;
      }
      function joinToString_0(_this__u8e3s4, separator, prefix, postfix, limit, truncated, transform2) {
        return joinTo_0(_this__u8e3s4, StringBuilder_init_$Create$_1(), separator, prefix, postfix, limit, truncated, transform2).toString();
      }
      function joinToString$default_0(_this__u8e3s4, separator, prefix, postfix, limit, truncated, transform2, $mask0, $handler) {
        if (!(($mask0 & 1) === 0))
          separator = ", ";
        if (!(($mask0 & 2) === 0))
          prefix = "";
        if (!(($mask0 & 4) === 0))
          postfix = "";
        if (!(($mask0 & 8) === 0))
          limit = -1;
        if (!(($mask0 & 16) === 0))
          truncated = "...";
        if (!(($mask0 & 32) === 0))
          transform2 = null;
        return joinToString_0(_this__u8e3s4, separator, prefix, postfix, limit, truncated, transform2);
      }
      function joinTo_0(_this__u8e3s4, buffer, separator, prefix, postfix, limit, truncated, transform2) {
        buffer.append_oz4qxs_k$(prefix);
        var count = 0;
        var tmp0_iterator = _this__u8e3s4.iterator_jk1svi_k$();
        $l$loop: while (tmp0_iterator.hasNext_bitz1p_k$()) {
          var element = tmp0_iterator.next_20eer_k$();
          count = count + 1 | 0;
          if (count > 1) {
            buffer.append_oz4qxs_k$(separator);
          }
          if (limit < 0 ? true : count <= limit) {
            appendElement(buffer, element, transform2);
          } else
            break $l$loop;
        }
        if (limit >= 0 ? count > limit : false) {
          buffer.append_oz4qxs_k$(truncated);
        }
        buffer.append_oz4qxs_k$(postfix);
        return buffer;
      }
      function joinTo$default_0(_this__u8e3s4, buffer, separator, prefix, postfix, limit, truncated, transform2, $mask0, $handler) {
        if (!(($mask0 & 2) === 0))
          separator = ", ";
        if (!(($mask0 & 4) === 0))
          prefix = "";
        if (!(($mask0 & 8) === 0))
          postfix = "";
        if (!(($mask0 & 16) === 0))
          limit = -1;
        if (!(($mask0 & 32) === 0))
          truncated = "...";
        if (!(($mask0 & 64) === 0))
          transform2 = null;
        return joinTo_0(_this__u8e3s4, buffer, separator, prefix, postfix, limit, truncated, transform2);
      }
      function until(_this__u8e3s4, to) {
        if (to <= IntCompanionObject_getInstance().MIN_VALUE_1)
          return Companion_getInstance_2().EMPTY_1;
        return numberRangeToNumber(_this__u8e3s4, to - 1 | 0);
      }
      function downTo(_this__u8e3s4, to) {
        return Companion_getInstance_5().fromClosedRange_vhxzyy_k$(_this__u8e3s4, to, -1);
      }
      function until_0(_this__u8e3s4, to) {
        Companion_getInstance_20();
        if (to.compareTo_n4fqi2_k$(new Long(0, -2147483648)) <= 0)
          return Companion_getInstance_4().EMPTY_1;
        var tmp$ret$0;
        tmp$ret$0 = to.minus_llf5ei_k$(new Long(1, 0));
        return _this__u8e3s4.rangeTo_5i95fi_k$(tmp$ret$0.toLong_edfucp_k$());
      }
      function reversed(_this__u8e3s4) {
        return Companion_getInstance_5().fromClosedRange_vhxzyy_k$(_this__u8e3s4.last_1, _this__u8e3s4.first_1, -_this__u8e3s4.step_1 | 0);
      }
      function getOrElse(_this__u8e3s4, index, defaultValue) {
        return (index >= 0 ? index <= get_lastIndex_7(_this__u8e3s4) : false) ? charSequenceGet(_this__u8e3s4, index) : defaultValue(index).value_1;
      }
      function contentEquals(_this__u8e3s4, other) {
        var tmp1_safe_receiver = _this__u8e3s4;
        var tmp;
        var tmp_0 = tmp1_safe_receiver;
        if ((tmp_0 == null ? null : new UByteArray(tmp_0)) == null) {
          tmp = null;
        } else {
          tmp = _UByteArray___get_storage__impl__d4kctt(tmp1_safe_receiver);
        }
        var tmp_1 = tmp;
        var tmp0_safe_receiver = other;
        var tmp_2;
        var tmp_3 = tmp0_safe_receiver;
        if ((tmp_3 == null ? null : new UByteArray(tmp_3)) == null) {
          tmp_2 = null;
        } else {
          tmp_2 = _UByteArray___get_storage__impl__d4kctt(tmp0_safe_receiver);
        }
        return contentEquals_3(tmp_1, tmp_2);
      }
      function contentEquals_0(_this__u8e3s4, other) {
        var tmp1_safe_receiver = _this__u8e3s4;
        var tmp;
        var tmp_0 = tmp1_safe_receiver;
        if ((tmp_0 == null ? null : new UIntArray(tmp_0)) == null) {
          tmp = null;
        } else {
          tmp = _UIntArray___get_storage__impl__92a0v0(tmp1_safe_receiver);
        }
        var tmp_1 = tmp;
        var tmp0_safe_receiver = other;
        var tmp_2;
        var tmp_3 = tmp0_safe_receiver;
        if ((tmp_3 == null ? null : new UIntArray(tmp_3)) == null) {
          tmp_2 = null;
        } else {
          tmp_2 = _UIntArray___get_storage__impl__92a0v0(tmp0_safe_receiver);
        }
        return contentEquals_4(tmp_1, tmp_2);
      }
      function contentEquals_1(_this__u8e3s4, other) {
        var tmp1_safe_receiver = _this__u8e3s4;
        var tmp;
        var tmp_0 = tmp1_safe_receiver;
        if ((tmp_0 == null ? null : new ULongArray(tmp_0)) == null) {
          tmp = null;
        } else {
          tmp = _ULongArray___get_storage__impl__28e64j(tmp1_safe_receiver);
        }
        var tmp_1 = tmp;
        var tmp0_safe_receiver = other;
        var tmp_2;
        var tmp_3 = tmp0_safe_receiver;
        if ((tmp_3 == null ? null : new ULongArray(tmp_3)) == null) {
          tmp_2 = null;
        } else {
          tmp_2 = _ULongArray___get_storage__impl__28e64j(tmp0_safe_receiver);
        }
        return contentEquals_5(tmp_1, tmp_2);
      }
      function contentEquals_2(_this__u8e3s4, other) {
        var tmp1_safe_receiver = _this__u8e3s4;
        var tmp;
        var tmp_0 = tmp1_safe_receiver;
        if ((tmp_0 == null ? null : new UShortArray(tmp_0)) == null) {
          tmp = null;
        } else {
          tmp = _UShortArray___get_storage__impl__t2jpv5(tmp1_safe_receiver);
        }
        var tmp_1 = tmp;
        var tmp0_safe_receiver = other;
        var tmp_2;
        var tmp_3 = tmp0_safe_receiver;
        if ((tmp_3 == null ? null : new UShortArray(tmp_3)) == null) {
          tmp_2 = null;
        } else {
          tmp_2 = _UShortArray___get_storage__impl__t2jpv5(tmp0_safe_receiver);
        }
        return contentEquals_6(tmp_1, tmp_2);
      }
      function KotlinNothingValueException_init_$Init$($this) {
        RuntimeException_init_$Init$($this);
        KotlinNothingValueException.call($this);
        return $this;
      }
      function KotlinNothingValueException_init_$Create$() {
        var tmp = KotlinNothingValueException_init_$Init$(Object.create(KotlinNothingValueException.prototype));
        captureStack(tmp, KotlinNothingValueException_init_$Create$);
        return tmp;
      }
      function KotlinNothingValueException_init_$Init$_0(message, $this) {
        RuntimeException_init_$Init$_0(message, $this);
        KotlinNothingValueException.call($this);
        return $this;
      }
      function KotlinNothingValueException_init_$Create$_0(message) {
        var tmp = KotlinNothingValueException_init_$Init$_0(message, Object.create(KotlinNothingValueException.prototype));
        captureStack(tmp, KotlinNothingValueException_init_$Create$_0);
        return tmp;
      }
      function KotlinNothingValueException_init_$Init$_1(message, cause, $this) {
        RuntimeException_init_$Init$_1(message, cause, $this);
        KotlinNothingValueException.call($this);
        return $this;
      }
      function KotlinNothingValueException_init_$Create$_1(message, cause) {
        var tmp = KotlinNothingValueException_init_$Init$_1(message, cause, Object.create(KotlinNothingValueException.prototype));
        captureStack(tmp, KotlinNothingValueException_init_$Create$_1);
        return tmp;
      }
      function KotlinNothingValueException_init_$Init$_2(cause, $this) {
        RuntimeException_init_$Init$_2(cause, $this);
        KotlinNothingValueException.call($this);
        return $this;
      }
      function KotlinNothingValueException_init_$Create$_2(cause) {
        var tmp = KotlinNothingValueException_init_$Init$_2(cause, Object.create(KotlinNothingValueException.prototype));
        captureStack(tmp, KotlinNothingValueException_init_$Create$_2);
        return tmp;
      }
      function KotlinNothingValueException() {
        captureStack(this, KotlinNothingValueException);
      }
      KotlinNothingValueException.$metadata$ = classMeta("KotlinNothingValueException", void 0, void 0, void 0, void 0, RuntimeException.prototype);
      function ExperimentalJsExport() {
      }
      ExperimentalJsExport.prototype.equals = function(other) {
        if (!(other instanceof ExperimentalJsExport))
          return false;
        var tmp0_other_with_cast = other instanceof ExperimentalJsExport ? other : THROW_CCE();
        return true;
      };
      ExperimentalJsExport.prototype.hashCode = function() {
        return 0;
      };
      ExperimentalJsExport.prototype.toString = function() {
        return "@kotlin.js.ExperimentalJsExport()";
      };
      ExperimentalJsExport.$metadata$ = classMeta("ExperimentalJsExport", [Annotation]);
      function get_PI() {
        return PI;
      }
      var PI;
      function get_code(_this__u8e3s4) {
        return Char__toInt_impl_vasixd(_this__u8e3s4);
      }
      function Char(code) {
        var tmp;
        var tmp$ret$0;
        Companion_getInstance_18();
        var tmp0__get_code__88qj9g = _Char___init__impl__6a9atx(0);
        tmp$ret$0 = Char__toInt_impl_vasixd(tmp0__get_code__88qj9g);
        if (code < tmp$ret$0) {
          tmp = true;
        } else {
          var tmp$ret$1;
          Companion_getInstance_18();
          var tmp1__get_code__adl84j = _Char___init__impl__6a9atx(65535);
          tmp$ret$1 = Char__toInt_impl_vasixd(tmp1__get_code__adl84j);
          tmp = code > tmp$ret$1;
        }
        if (tmp) {
          throw IllegalArgumentException_init_$Create$_0("Invalid Char code: " + code);
        }
        return numberToChar(code);
      }
      function WasExperimental(markerClass) {
        this.markerClass_1 = markerClass;
      }
      WasExperimental.prototype.get_markerClass_h8iub9_k$ = function() {
        return this.markerClass_1;
      };
      WasExperimental.prototype.equals = function(other) {
        if (!(other instanceof WasExperimental))
          return false;
        var tmp0_other_with_cast = other instanceof WasExperimental ? other : THROW_CCE();
        if (!contentEquals_7(this.markerClass_1, tmp0_other_with_cast.markerClass_1))
          return false;
        return true;
      };
      WasExperimental.prototype.hashCode = function() {
        return imul(getStringHashCode("markerClass"), 127) ^ hashCode(this.markerClass_1);
      };
      WasExperimental.prototype.toString = function() {
        return "@kotlin.WasExperimental(markerClass=" + toString_1(this.markerClass_1) + ")";
      };
      WasExperimental.$metadata$ = classMeta("WasExperimental", [Annotation]);
      function ExperimentalStdlibApi() {
      }
      ExperimentalStdlibApi.prototype.equals = function(other) {
        if (!(other instanceof ExperimentalStdlibApi))
          return false;
        var tmp0_other_with_cast = other instanceof ExperimentalStdlibApi ? other : THROW_CCE();
        return true;
      };
      ExperimentalStdlibApi.prototype.hashCode = function() {
        return 0;
      };
      ExperimentalStdlibApi.prototype.toString = function() {
        return "@kotlin.ExperimentalStdlibApi()";
      };
      ExperimentalStdlibApi.$metadata$ = classMeta("ExperimentalStdlibApi", [Annotation]);
      function OptionalExpectation() {
      }
      OptionalExpectation.prototype.equals = function(other) {
        if (!(other instanceof OptionalExpectation))
          return false;
        var tmp0_other_with_cast = other instanceof OptionalExpectation ? other : THROW_CCE();
        return true;
      };
      OptionalExpectation.prototype.hashCode = function() {
        return 0;
      };
      OptionalExpectation.prototype.toString = function() {
        return "@kotlin.OptionalExpectation()";
      };
      OptionalExpectation.$metadata$ = classMeta("OptionalExpectation", [Annotation]);
      function ExperimentalMultiplatform() {
      }
      ExperimentalMultiplatform.prototype.equals = function(other) {
        if (!(other instanceof ExperimentalMultiplatform))
          return false;
        var tmp0_other_with_cast = other instanceof ExperimentalMultiplatform ? other : THROW_CCE();
        return true;
      };
      ExperimentalMultiplatform.prototype.hashCode = function() {
        return 0;
      };
      ExperimentalMultiplatform.prototype.toString = function() {
        return "@kotlin.ExperimentalMultiplatform()";
      };
      ExperimentalMultiplatform.$metadata$ = classMeta("ExperimentalMultiplatform", [Annotation]);
      var Level_WARNING_instance;
      var Level_ERROR_instance;
      function values() {
        return [Level_WARNING_getInstance(), Level_ERROR_getInstance()];
      }
      function valueOf(value) {
        switch (value) {
          case "WARNING":
            return Level_WARNING_getInstance();
          case "ERROR":
            return Level_ERROR_getInstance();
          default:
            Level_initEntries();
            THROW_ISE();
            break;
        }
      }
      var Level_entriesInitialized;
      function Level_initEntries() {
        if (Level_entriesInitialized)
          return Unit_getInstance();
        Level_entriesInitialized = true;
        Level_WARNING_instance = new Level("WARNING", 0);
        Level_ERROR_instance = new Level("ERROR", 1);
      }
      function RequiresOptIn_init_$Init$(message, level, $mask0, $marker, $this) {
        if (!(($mask0 & 1) === 0))
          message = "";
        if (!(($mask0 & 2) === 0))
          level = Level_ERROR_getInstance();
        RequiresOptIn.call($this, message, level);
        return $this;
      }
      function RequiresOptIn_init_$Create$(message, level, $mask0, $marker) {
        return RequiresOptIn_init_$Init$(message, level, $mask0, $marker, Object.create(RequiresOptIn.prototype));
      }
      function Level(name, ordinal) {
        Enum.call(this, name, ordinal);
      }
      Level.$metadata$ = classMeta("Level", void 0, void 0, void 0, void 0, Enum.prototype);
      function Level_WARNING_getInstance() {
        Level_initEntries();
        return Level_WARNING_instance;
      }
      function Level_ERROR_getInstance() {
        Level_initEntries();
        return Level_ERROR_instance;
      }
      function RequiresOptIn(message, level) {
        this.message_1 = message;
        this.level_1 = level;
      }
      RequiresOptIn.prototype.get_message_h23axq_k$ = function() {
        return this.message_1;
      };
      RequiresOptIn.prototype.get_level_ium7h7_k$ = function() {
        return this.level_1;
      };
      RequiresOptIn.prototype.equals = function(other) {
        if (!(other instanceof RequiresOptIn))
          return false;
        var tmp0_other_with_cast = other instanceof RequiresOptIn ? other : THROW_CCE();
        if (!(this.message_1 === tmp0_other_with_cast.message_1))
          return false;
        if (!this.level_1.equals(tmp0_other_with_cast.level_1))
          return false;
        return true;
      };
      RequiresOptIn.prototype.hashCode = function() {
        var result = imul(getStringHashCode("message"), 127) ^ getStringHashCode(this.message_1);
        result = result + (imul(getStringHashCode("level"), 127) ^ this.level_1.hashCode()) | 0;
        return result;
      };
      RequiresOptIn.prototype.toString = function() {
        return "@kotlin.RequiresOptIn(message=" + this.message_1 + ", level=" + this.level_1 + ")";
      };
      RequiresOptIn.$metadata$ = classMeta("RequiresOptIn", [Annotation]);
      function OptIn(markerClass) {
        this.markerClass_1 = markerClass;
      }
      OptIn.prototype.get_markerClass_h8iub9_k$ = function() {
        return this.markerClass_1;
      };
      OptIn.prototype.equals = function(other) {
        if (!(other instanceof OptIn))
          return false;
        var tmp0_other_with_cast = other instanceof OptIn ? other : THROW_CCE();
        if (!contentEquals_7(this.markerClass_1, tmp0_other_with_cast.markerClass_1))
          return false;
        return true;
      };
      OptIn.prototype.hashCode = function() {
        return imul(getStringHashCode("markerClass"), 127) ^ hashCode(this.markerClass_1);
      };
      OptIn.prototype.toString = function() {
        return "@kotlin.OptIn(markerClass=" + toString_1(this.markerClass_1) + ")";
      };
      OptIn.$metadata$ = classMeta("OptIn", [Annotation]);
      function AbstractCollection$toString$lambda(this$0) {
        return function(it) {
          return it === this$0 ? "(this Collection)" : toString_0(it);
        };
      }
      function AbstractCollection() {
      }
      AbstractCollection.prototype.contains_2ehdt1_k$ = function(element) {
        var tmp$ret$0;
        $l$block_0: {
          var tmp;
          if (isInterface(this, Collection)) {
            tmp = this.isEmpty_y1axqb_k$();
          } else {
            tmp = false;
          }
          if (tmp) {
            tmp$ret$0 = false;
            break $l$block_0;
          }
          var tmp0_iterator = this.iterator_jk1svi_k$();
          while (tmp0_iterator.hasNext_bitz1p_k$()) {
            var element_0 = tmp0_iterator.next_20eer_k$();
            var tmp$ret$1;
            tmp$ret$1 = equals(element_0, element);
            if (tmp$ret$1) {
              tmp$ret$0 = true;
              break $l$block_0;
            }
          }
          tmp$ret$0 = false;
        }
        return tmp$ret$0;
      };
      AbstractCollection.prototype.containsAll_jr3fla_k$ = function(elements) {
        var tmp$ret$0;
        $l$block_0: {
          var tmp;
          if (isInterface(elements, Collection)) {
            tmp = elements.isEmpty_y1axqb_k$();
          } else {
            tmp = false;
          }
          if (tmp) {
            tmp$ret$0 = true;
            break $l$block_0;
          }
          var tmp0_iterator = elements.iterator_jk1svi_k$();
          while (tmp0_iterator.hasNext_bitz1p_k$()) {
            var element = tmp0_iterator.next_20eer_k$();
            var tmp$ret$1;
            tmp$ret$1 = this.contains_2ehdt1_k$(element);
            if (!tmp$ret$1) {
              tmp$ret$0 = false;
              break $l$block_0;
            }
          }
          tmp$ret$0 = true;
        }
        return tmp$ret$0;
      };
      AbstractCollection.prototype.isEmpty_y1axqb_k$ = function() {
        return this.get_size_woubt6_k$() === 0;
      };
      AbstractCollection.prototype.toString = function() {
        return joinToString$default_0(this, ", ", "[", "]", 0, null, AbstractCollection$toString$lambda(this), 24, null);
      };
      AbstractCollection.prototype.toArray = function() {
        return copyToArrayImpl(this);
      };
      AbstractCollection.prototype.toArray_nu7pb_k$ = function(array3) {
        return copyToExistingArrayImpl(this, array3);
      };
      AbstractCollection.$metadata$ = classMeta("AbstractCollection", [Collection]);
      function _get_list__d9tsa5($this) {
        return $this.list_1;
      }
      function _get_fromIndex__987b49($this) {
        return $this.fromIndex_1;
      }
      function _set__size__bau3qd($this, _set____db54di) {
        $this._size_1 = _set____db54di;
      }
      function _get__size__kqacr3($this) {
        return $this._size_1;
      }
      function SubList(list, fromIndex, toIndex) {
        AbstractList.call(this);
        this.list_1 = list;
        this.fromIndex_1 = fromIndex;
        this._size_1 = 0;
        Companion_getInstance().checkRangeIndexes_5hjybp_k$(this.fromIndex_1, toIndex, this.list_1.get_size_woubt6_k$());
        this._size_1 = toIndex - this.fromIndex_1 | 0;
      }
      SubList.prototype.get_fkrdnv_k$ = function(index) {
        Companion_getInstance().checkElementIndex_ux0wz1_k$(index, this._size_1);
        return this.list_1.get_fkrdnv_k$(this.fromIndex_1 + index | 0);
      };
      SubList.prototype.get_size_woubt6_k$ = function() {
        return this._size_1;
      };
      SubList.$metadata$ = classMeta("SubList", [RandomAccess], void 0, void 0, void 0, AbstractList.prototype);
      function IteratorImpl($outer) {
        this.$this_1 = $outer;
        this.index_1 = 0;
      }
      IteratorImpl.prototype.set_index_eknhut_k$ = function(_set____db54di) {
        this.index_1 = _set____db54di;
      };
      IteratorImpl.prototype.get_index_it478p_k$ = function() {
        return this.index_1;
      };
      IteratorImpl.prototype.hasNext_bitz1p_k$ = function() {
        return this.index_1 < this.$this_1.get_size_woubt6_k$();
      };
      IteratorImpl.prototype.next_20eer_k$ = function() {
        if (!this.hasNext_bitz1p_k$())
          throw NoSuchElementException_init_$Create$();
        var tmp0_this = this;
        var tmp1 = tmp0_this.index_1;
        tmp0_this.index_1 = tmp1 + 1 | 0;
        return this.$this_1.get_fkrdnv_k$(tmp1);
      };
      IteratorImpl.$metadata$ = classMeta("IteratorImpl", [Iterator_3]);
      function ListIteratorImpl($outer, index) {
        this.$this_2 = $outer;
        IteratorImpl.call(this, $outer);
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this.$this_2.get_size_woubt6_k$());
        this.index_1 = index;
      }
      ListIteratorImpl.prototype.hasPrevious_qh0629_k$ = function() {
        return this.index_1 > 0;
      };
      ListIteratorImpl.prototype.nextIndex_jshxun_k$ = function() {
        return this.index_1;
      };
      ListIteratorImpl.prototype.previous_l2dfd5_k$ = function() {
        if (!this.hasPrevious_qh0629_k$())
          throw NoSuchElementException_init_$Create$();
        var tmp0_this = this;
        tmp0_this.index_1 = tmp0_this.index_1 - 1 | 0;
        return this.$this_2.get_fkrdnv_k$(tmp0_this.index_1);
      };
      ListIteratorImpl.prototype.previousIndex_4qtyw5_k$ = function() {
        return this.index_1 - 1 | 0;
      };
      ListIteratorImpl.$metadata$ = classMeta("ListIteratorImpl", [ListIterator], void 0, void 0, void 0, IteratorImpl.prototype);
      function Companion() {
        Companion_instance = this;
      }
      Companion.prototype.checkElementIndex_ux0wz1_k$ = function(index, size2) {
        if (index < 0 ? true : index >= size2) {
          throw IndexOutOfBoundsException_init_$Create$_0("index: " + index + ", size: " + size2);
        }
      };
      Companion.prototype.checkPositionIndex_kxpgsw_k$ = function(index, size2) {
        if (index < 0 ? true : index > size2) {
          throw IndexOutOfBoundsException_init_$Create$_0("index: " + index + ", size: " + size2);
        }
      };
      Companion.prototype.checkRangeIndexes_5hjybp_k$ = function(fromIndex, toIndex, size2) {
        if (fromIndex < 0 ? true : toIndex > size2) {
          throw IndexOutOfBoundsException_init_$Create$_0("fromIndex: " + fromIndex + ", toIndex: " + toIndex + ", size: " + size2);
        }
        if (fromIndex > toIndex) {
          throw IllegalArgumentException_init_$Create$_0("fromIndex: " + fromIndex + " > toIndex: " + toIndex);
        }
      };
      Companion.prototype.checkBoundsIndexes_7787d9_k$ = function(startIndex, endIndex, size2) {
        if (startIndex < 0 ? true : endIndex > size2) {
          throw IndexOutOfBoundsException_init_$Create$_0("startIndex: " + startIndex + ", endIndex: " + endIndex + ", size: " + size2);
        }
        if (startIndex > endIndex) {
          throw IllegalArgumentException_init_$Create$_0("startIndex: " + startIndex + " > endIndex: " + endIndex);
        }
      };
      Companion.prototype.orderedHashCode_2n0xp_k$ = function(c) {
        var hashCode_02 = 1;
        var tmp0_iterator = c.iterator_jk1svi_k$();
        while (tmp0_iterator.hasNext_bitz1p_k$()) {
          var e = tmp0_iterator.next_20eer_k$();
          var tmp = imul(31, hashCode_02);
          var tmp1_safe_receiver = e;
          var tmp2_elvis_lhs = tmp1_safe_receiver == null ? null : hashCode(tmp1_safe_receiver);
          hashCode_02 = tmp + (tmp2_elvis_lhs == null ? 0 : tmp2_elvis_lhs) | 0;
        }
        return hashCode_02;
      };
      Companion.prototype.orderedEquals_40uhas_k$ = function(c, other) {
        if (!(c.get_size_woubt6_k$() === other.get_size_woubt6_k$()))
          return false;
        var otherIterator = other.iterator_jk1svi_k$();
        var tmp0_iterator = c.iterator_jk1svi_k$();
        while (tmp0_iterator.hasNext_bitz1p_k$()) {
          var elem = tmp0_iterator.next_20eer_k$();
          var elemOther = otherIterator.next_20eer_k$();
          if (!equals(elem, elemOther)) {
            return false;
          }
        }
        return true;
      };
      Companion.$metadata$ = objectMeta("Companion");
      var Companion_instance;
      function Companion_getInstance() {
        if (Companion_instance == null)
          new Companion();
        return Companion_instance;
      }
      function AbstractList() {
        Companion_getInstance();
        AbstractCollection.call(this);
      }
      AbstractList.prototype.iterator_jk1svi_k$ = function() {
        return new IteratorImpl(this);
      };
      AbstractList.prototype.indexOf_dcv8dt_k$ = function(element) {
        var tmp$ret$1;
        $l$block: {
          var index = 0;
          var tmp0_iterator = this.iterator_jk1svi_k$();
          while (tmp0_iterator.hasNext_bitz1p_k$()) {
            var item = tmp0_iterator.next_20eer_k$();
            var tmp$ret$0;
            tmp$ret$0 = equals(item, element);
            if (tmp$ret$0) {
              tmp$ret$1 = index;
              break $l$block;
            }
            var tmp1 = index;
            index = tmp1 + 1 | 0;
          }
          tmp$ret$1 = -1;
        }
        return tmp$ret$1;
      };
      AbstractList.prototype.lastIndexOf_rzx8t5_k$ = function(element) {
        var tmp$ret$1;
        $l$block: {
          var iterator = this.listIterator_5hanv9_k$(this.get_size_woubt6_k$());
          while (iterator.hasPrevious_qh0629_k$()) {
            var tmp$ret$0;
            var tmp0__anonymous__q1qw7t = iterator.previous_l2dfd5_k$();
            tmp$ret$0 = equals(tmp0__anonymous__q1qw7t, element);
            if (tmp$ret$0) {
              tmp$ret$1 = iterator.nextIndex_jshxun_k$();
              break $l$block;
            }
          }
          tmp$ret$1 = -1;
        }
        return tmp$ret$1;
      };
      AbstractList.prototype.listIterator_xjshxw_k$ = function() {
        return new ListIteratorImpl(this, 0);
      };
      AbstractList.prototype.listIterator_5hanv9_k$ = function(index) {
        return new ListIteratorImpl(this, index);
      };
      AbstractList.prototype.subList_d153ha_k$ = function(fromIndex, toIndex) {
        return new SubList(this, fromIndex, toIndex);
      };
      AbstractList.prototype.equals = function(other) {
        if (other === this)
          return true;
        if (!(!(other == null) ? isInterface(other, List) : false))
          return false;
        return Companion_getInstance().orderedEquals_40uhas_k$(this, other);
      };
      AbstractList.prototype.hashCode = function() {
        return Companion_getInstance().orderedHashCode_2n0xp_k$(this);
      };
      AbstractList.$metadata$ = classMeta("AbstractList", [List], void 0, void 0, void 0, AbstractCollection.prototype);
      function get_indices_6(_this__u8e3s4) {
        return numberRangeToNumber(0, _this__u8e3s4.get_size_woubt6_k$() - 1 | 0);
      }
      function get_lastIndex_6(_this__u8e3s4) {
        return _this__u8e3s4.get_size_woubt6_k$() - 1 | 0;
      }
      function emptyList() {
        return EmptyList_getInstance();
      }
      function _get_serialVersionUID__fhggm9($this) {
        return $this.serialVersionUID_1;
      }
      function readResolve($this) {
        return EmptyList_getInstance();
      }
      function EmptyList() {
        EmptyList_instance = this;
        this.serialVersionUID_1 = new Long(-1478467534, -1720727600);
      }
      EmptyList.prototype.equals = function(other) {
        var tmp;
        if (!(other == null) ? isInterface(other, List) : false) {
          tmp = other.isEmpty_y1axqb_k$();
        } else {
          tmp = false;
        }
        return tmp;
      };
      EmptyList.prototype.hashCode = function() {
        return 1;
      };
      EmptyList.prototype.toString = function() {
        return "[]";
      };
      EmptyList.prototype.get_size_woubt6_k$ = function() {
        return 0;
      };
      EmptyList.prototype.isEmpty_y1axqb_k$ = function() {
        return true;
      };
      EmptyList.prototype.contains_a7ux40_k$ = function(element) {
        return false;
      };
      EmptyList.prototype.contains_2ehdt1_k$ = function(element) {
        if (true)
          return false;
        var tmp;
        if (false) {
          tmp = element;
        } else {
          tmp = THROW_CCE();
        }
        return this.contains_a7ux40_k$(tmp);
      };
      EmptyList.prototype.containsAll_4bfz49_k$ = function(elements) {
        return elements.isEmpty_y1axqb_k$();
      };
      EmptyList.prototype.containsAll_jr3fla_k$ = function(elements) {
        return this.containsAll_4bfz49_k$(elements);
      };
      EmptyList.prototype.get_fkrdnv_k$ = function(index) {
        throw IndexOutOfBoundsException_init_$Create$_0("Empty list doesn't contain element at index " + index + ".");
      };
      EmptyList.prototype.indexOf_31ms1i_k$ = function(element) {
        return -1;
      };
      EmptyList.prototype.indexOf_dcv8dt_k$ = function(element) {
        if (true)
          return -1;
        var tmp;
        if (false) {
          tmp = element;
        } else {
          tmp = THROW_CCE();
        }
        return this.indexOf_31ms1i_k$(tmp);
      };
      EmptyList.prototype.lastIndexOf_5pkqqc_k$ = function(element) {
        return -1;
      };
      EmptyList.prototype.lastIndexOf_rzx8t5_k$ = function(element) {
        if (true)
          return -1;
        var tmp;
        if (false) {
          tmp = element;
        } else {
          tmp = THROW_CCE();
        }
        return this.lastIndexOf_5pkqqc_k$(tmp);
      };
      EmptyList.prototype.iterator_jk1svi_k$ = function() {
        return EmptyIterator_getInstance();
      };
      EmptyList.prototype.listIterator_xjshxw_k$ = function() {
        return EmptyIterator_getInstance();
      };
      EmptyList.prototype.listIterator_5hanv9_k$ = function(index) {
        if (!(index === 0))
          throw IndexOutOfBoundsException_init_$Create$_0("Index: " + index);
        return EmptyIterator_getInstance();
      };
      EmptyList.prototype.subList_d153ha_k$ = function(fromIndex, toIndex) {
        if (fromIndex === 0 ? toIndex === 0 : false)
          return this;
        throw IndexOutOfBoundsException_init_$Create$_0("fromIndex: " + fromIndex + ", toIndex: " + toIndex);
      };
      EmptyList.$metadata$ = objectMeta("EmptyList", [List, Serializable, RandomAccess]);
      var EmptyList_instance;
      function EmptyList_getInstance() {
        if (EmptyList_instance == null)
          new EmptyList();
        return EmptyList_instance;
      }
      function EmptyIterator() {
        EmptyIterator_instance = this;
      }
      EmptyIterator.prototype.hasNext_bitz1p_k$ = function() {
        return false;
      };
      EmptyIterator.prototype.hasPrevious_qh0629_k$ = function() {
        return false;
      };
      EmptyIterator.prototype.nextIndex_jshxun_k$ = function() {
        return 0;
      };
      EmptyIterator.prototype.previousIndex_4qtyw5_k$ = function() {
        return -1;
      };
      EmptyIterator.prototype.next_20eer_k$ = function() {
        throw NoSuchElementException_init_$Create$();
      };
      EmptyIterator.prototype.previous_l2dfd5_k$ = function() {
        throw NoSuchElementException_init_$Create$();
      };
      EmptyIterator.$metadata$ = objectMeta("EmptyIterator", [ListIterator]);
      var EmptyIterator_instance;
      function EmptyIterator_getInstance() {
        if (EmptyIterator_instance == null)
          new EmptyIterator();
        return EmptyIterator_instance;
      }
      function removeAll(_this__u8e3s4, predicate) {
        return filterInPlace(_this__u8e3s4, predicate, true);
      }
      function removeAll_0(_this__u8e3s4, predicate) {
        return filterInPlace_0(_this__u8e3s4, predicate, true);
      }
      function filterInPlace(_this__u8e3s4, predicate, predicateResultToRemove) {
        if (!isInterface(_this__u8e3s4, RandomAccess)) {
          return filterInPlace_0(isInterface(_this__u8e3s4, MutableIterable) ? _this__u8e3s4 : THROW_CCE(), predicate, predicateResultToRemove);
        }
        var writeIndex = 0;
        var inductionVariable = 0;
        var last = get_lastIndex_6(_this__u8e3s4);
        if (inductionVariable <= last)
          $l$loop: do {
            var readIndex = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var element = _this__u8e3s4.get_fkrdnv_k$(readIndex);
            if (predicate(element) === predicateResultToRemove)
              continue $l$loop;
            if (!(writeIndex === readIndex)) {
              _this__u8e3s4.set_meu351_k$(writeIndex, element);
            }
            var tmp1 = writeIndex;
            writeIndex = tmp1 + 1 | 0;
          } while (!(readIndex === last));
        if (writeIndex < _this__u8e3s4.get_size_woubt6_k$()) {
          var inductionVariable_0 = get_lastIndex_6(_this__u8e3s4);
          var last_0 = writeIndex;
          if (last_0 <= inductionVariable_0)
            do {
              var removeIndex = inductionVariable_0;
              inductionVariable_0 = inductionVariable_0 + -1 | 0;
              _this__u8e3s4.removeAt_qvpkxi_k$(removeIndex);
            } while (!(removeIndex === last_0));
          return true;
        } else {
          return false;
        }
      }
      function filterInPlace_0(_this__u8e3s4, predicate, predicateResultToRemove) {
        var result = false;
        var tmp$ret$0;
        var tmp0_with = _this__u8e3s4.iterator_jk1svi_k$();
        while (tmp0_with.hasNext_bitz1p_k$())
          if (predicate(tmp0_with.next_20eer_k$()) === predicateResultToRemove) {
            tmp0_with.remove_le47v1_k$();
            result = true;
          }
        tmp$ret$0 = Unit_getInstance();
        return result;
      }
      function IntIterator() {
      }
      IntIterator.prototype.next_20eer_k$ = function() {
        return this.nextInt_ujorgc_k$();
      };
      IntIterator.$metadata$ = classMeta("IntIterator", [Iterator_3]);
      function ByteIterator() {
      }
      ByteIterator.prototype.next_20eer_k$ = function() {
        return this.nextByte_njqopn_k$();
      };
      ByteIterator.$metadata$ = classMeta("ByteIterator", [Iterator_3]);
      function DoubleIterator() {
      }
      DoubleIterator.prototype.next_20eer_k$ = function() {
        return this.nextDouble_s2xvfg_k$();
      };
      DoubleIterator.$metadata$ = classMeta("DoubleIterator", [Iterator_3]);
      function FloatIterator() {
      }
      FloatIterator.prototype.next_20eer_k$ = function() {
        return this.nextFloat_jqti5l_k$();
      };
      FloatIterator.$metadata$ = classMeta("FloatIterator", [Iterator_3]);
      function CharIterator() {
      }
      CharIterator.prototype.next_31h2mk_k$ = function() {
        return this.nextChar_yv3rl6_k$();
      };
      CharIterator.prototype.next_20eer_k$ = function() {
        return new Char_0(this.next_31h2mk_k$());
      };
      CharIterator.$metadata$ = classMeta("CharIterator", [Iterator_3]);
      function LongIterator() {
      }
      LongIterator.prototype.next_20eer_k$ = function() {
        return this.nextLong_njwv0v_k$();
      };
      LongIterator.$metadata$ = classMeta("LongIterator", [Iterator_3]);
      function ShortIterator() {
      }
      ShortIterator.prototype.next_20eer_k$ = function() {
        return this.nextShort_jxwabt_k$();
      };
      ShortIterator.$metadata$ = classMeta("ShortIterator", [Iterator_3]);
      function BooleanIterator() {
      }
      BooleanIterator.prototype.next_20eer_k$ = function() {
        return this.nextBoolean_nfdk1h_k$();
      };
      BooleanIterator.$metadata$ = classMeta("BooleanIterator", [Iterator_3]);
      function Sequence2() {
      }
      Sequence2.$metadata$ = interfaceMeta("Sequence");
      function contract(builder) {
      }
      function ContractBuilder() {
      }
      ContractBuilder.$metadata$ = interfaceMeta("ContractBuilder");
      var InvocationKind_AT_MOST_ONCE_instance;
      var InvocationKind_AT_LEAST_ONCE_instance;
      var InvocationKind_EXACTLY_ONCE_instance;
      var InvocationKind_UNKNOWN_instance;
      function values_0() {
        return [InvocationKind_AT_MOST_ONCE_getInstance(), InvocationKind_AT_LEAST_ONCE_getInstance(), InvocationKind_EXACTLY_ONCE_getInstance(), InvocationKind_UNKNOWN_getInstance()];
      }
      function valueOf_0(value) {
        switch (value) {
          case "AT_MOST_ONCE":
            return InvocationKind_AT_MOST_ONCE_getInstance();
          case "AT_LEAST_ONCE":
            return InvocationKind_AT_LEAST_ONCE_getInstance();
          case "EXACTLY_ONCE":
            return InvocationKind_EXACTLY_ONCE_getInstance();
          case "UNKNOWN":
            return InvocationKind_UNKNOWN_getInstance();
          default:
            InvocationKind_initEntries();
            THROW_ISE();
            break;
        }
      }
      var InvocationKind_entriesInitialized;
      function InvocationKind_initEntries() {
        if (InvocationKind_entriesInitialized)
          return Unit_getInstance();
        InvocationKind_entriesInitialized = true;
        InvocationKind_AT_MOST_ONCE_instance = new InvocationKind("AT_MOST_ONCE", 0);
        InvocationKind_AT_LEAST_ONCE_instance = new InvocationKind("AT_LEAST_ONCE", 1);
        InvocationKind_EXACTLY_ONCE_instance = new InvocationKind("EXACTLY_ONCE", 2);
        InvocationKind_UNKNOWN_instance = new InvocationKind("UNKNOWN", 3);
      }
      function InvocationKind(name, ordinal) {
        Enum.call(this, name, ordinal);
      }
      InvocationKind.$metadata$ = classMeta("InvocationKind", void 0, void 0, void 0, void 0, Enum.prototype);
      function ExperimentalContracts() {
      }
      ExperimentalContracts.prototype.equals = function(other) {
        if (!(other instanceof ExperimentalContracts))
          return false;
        var tmp0_other_with_cast = other instanceof ExperimentalContracts ? other : THROW_CCE();
        return true;
      };
      ExperimentalContracts.prototype.hashCode = function() {
        return 0;
      };
      ExperimentalContracts.prototype.toString = function() {
        return "@kotlin.contracts.ExperimentalContracts()";
      };
      ExperimentalContracts.$metadata$ = classMeta("ExperimentalContracts", [Annotation]);
      function InvocationKind_AT_MOST_ONCE_getInstance() {
        InvocationKind_initEntries();
        return InvocationKind_AT_MOST_ONCE_instance;
      }
      function InvocationKind_AT_LEAST_ONCE_getInstance() {
        InvocationKind_initEntries();
        return InvocationKind_AT_LEAST_ONCE_instance;
      }
      function InvocationKind_EXACTLY_ONCE_getInstance() {
        InvocationKind_initEntries();
        return InvocationKind_EXACTLY_ONCE_instance;
      }
      function InvocationKind_UNKNOWN_getInstance() {
        InvocationKind_initEntries();
        return InvocationKind_UNKNOWN_instance;
      }
      function CallsInPlace() {
      }
      CallsInPlace.$metadata$ = interfaceMeta("CallsInPlace", [Effect]);
      function Returns() {
      }
      Returns.$metadata$ = interfaceMeta("Returns", [SimpleEffect]);
      function ReturnsNotNull() {
      }
      ReturnsNotNull.$metadata$ = interfaceMeta("ReturnsNotNull", [SimpleEffect]);
      function Effect() {
      }
      Effect.$metadata$ = interfaceMeta("Effect");
      function SimpleEffect() {
      }
      SimpleEffect.$metadata$ = interfaceMeta("SimpleEffect", [Effect]);
      function ConditionalEffect() {
      }
      ConditionalEffect.$metadata$ = interfaceMeta("ConditionalEffect", [Effect]);
      function Continuation() {
      }
      Continuation.$metadata$ = interfaceMeta("Continuation");
      function Continuation_0(context, resumeWith) {
        return new _no_name_provided__qut3iv(context, resumeWith);
      }
      function resumeWithException(_this__u8e3s4, exception) {
        var tmp$ret$0;
        var tmp0_failure = Companion_getInstance_9();
        tmp$ret$0 = _Result___init__impl__xyqfz8(createFailure(exception));
        return _this__u8e3s4.resumeWith_s3a3yh_k$(tmp$ret$0);
      }
      function resume(_this__u8e3s4, value) {
        var tmp$ret$0;
        var tmp0_success = Companion_getInstance_9();
        tmp$ret$0 = _Result___init__impl__xyqfz8(value);
        return _this__u8e3s4.resumeWith_s3a3yh_k$(tmp$ret$0);
      }
      function get_coroutineContext() {
        throw new NotImplementedError("Implemented as intrinsic");
      }
      function _no_name_provided__qut3iv($context, $resumeWith) {
        this.$context_1 = $context;
        this.$resumeWith_1 = $resumeWith;
      }
      _no_name_provided__qut3iv.prototype.get_context_h02k06_k$ = function() {
        return this.$context_1;
      };
      _no_name_provided__qut3iv.prototype.resumeWith_s3a3yh_k$ = function(result) {
        return this.$resumeWith_1(new Result(result));
      };
      _no_name_provided__qut3iv.$metadata$ = classMeta(void 0, [Continuation]);
      function Key() {
        Key_instance = this;
      }
      Key.$metadata$ = objectMeta("Key", [Key_0]);
      var Key_instance;
      function Key_getInstance() {
        if (Key_instance == null)
          new Key();
        return Key_instance;
      }
      function ContinuationInterceptor() {
        Key_getInstance();
      }
      ContinuationInterceptor.$metadata$ = interfaceMeta("ContinuationInterceptor", [Element2]);
      function Key_0() {
      }
      Key_0.$metadata$ = interfaceMeta("Key");
      function Element2() {
      }
      Element2.$metadata$ = interfaceMeta("Element", [CoroutineContext]);
      function CoroutineContext$plus$lambda(acc, element) {
        var removed = acc.minusKey_y21q55_k$(element.get_key_18j28a_k$());
        var tmp;
        if (removed === EmptyCoroutineContext_getInstance()) {
          tmp = element;
        } else {
          var interceptor = removed.get_1pi7hg_k$(Key_getInstance());
          var tmp_0;
          if (interceptor == null) {
            tmp_0 = new CombinedContext(removed, element);
          } else {
            var left2 = removed.minusKey_y21q55_k$(Key_getInstance());
            tmp_0 = left2 === EmptyCoroutineContext_getInstance() ? new CombinedContext(element, interceptor) : new CombinedContext(new CombinedContext(left2, element), interceptor);
          }
          tmp = tmp_0;
        }
        return tmp;
      }
      function CoroutineContext() {
      }
      CoroutineContext.$metadata$ = interfaceMeta("CoroutineContext");
      function _get_serialVersionUID__fhggm9_0($this) {
        return $this.serialVersionUID_1;
      }
      function readResolve_0($this) {
        return EmptyCoroutineContext_getInstance();
      }
      function EmptyCoroutineContext() {
        EmptyCoroutineContext_instance = this;
        this.serialVersionUID_1 = new Long(0, 0);
      }
      EmptyCoroutineContext.prototype.get_1pi7hg_k$ = function(key) {
        return null;
      };
      EmptyCoroutineContext.prototype.fold_6dbyow_k$ = function(initial, operation) {
        return initial;
      };
      EmptyCoroutineContext.prototype.plus_rgw9wi_k$ = function(context) {
        return context;
      };
      EmptyCoroutineContext.prototype.minusKey_y21q55_k$ = function(key) {
        return this;
      };
      EmptyCoroutineContext.prototype.hashCode = function() {
        return 0;
      };
      EmptyCoroutineContext.prototype.toString = function() {
        return "EmptyCoroutineContext";
      };
      EmptyCoroutineContext.$metadata$ = objectMeta("EmptyCoroutineContext", [CoroutineContext, Serializable]);
      var EmptyCoroutineContext_instance;
      function EmptyCoroutineContext_getInstance() {
        if (EmptyCoroutineContext_instance == null)
          new EmptyCoroutineContext();
        return EmptyCoroutineContext_instance;
      }
      function _get_serialVersionUID__fhggm9_1($this) {
        return $this.serialVersionUID_1;
      }
      function Companion_0() {
        Companion_instance_0 = this;
        this.serialVersionUID_1 = new Long(0, 0);
      }
      Companion_0.$metadata$ = objectMeta("Companion");
      var Companion_instance_0;
      function Companion_getInstance_0() {
        if (Companion_instance_0 == null)
          new Companion_0();
        return Companion_instance_0;
      }
      function readResolve_1($this) {
        var tmp$ret$0;
        var tmp0_fold = $this.elements_1;
        var tmp1_fold = EmptyCoroutineContext_getInstance();
        var accumulator = tmp1_fold;
        var indexedObject = tmp0_fold;
        var inductionVariable = 0;
        var last = indexedObject.length;
        while (inductionVariable < last) {
          var element = indexedObject[inductionVariable];
          inductionVariable = inductionVariable + 1 | 0;
          accumulator = accumulator.plus_rgw9wi_k$(element);
        }
        tmp$ret$0 = accumulator;
        return tmp$ret$0;
      }
      function _get_left__d9qyp0($this) {
        return $this.left_1;
      }
      function _get_element__z0t21h($this) {
        return $this.element_1;
      }
      function size($this) {
        var cur = $this;
        var size2 = 2;
        while (true) {
          var tmp = cur.left_1;
          var tmp0_elvis_lhs = tmp instanceof CombinedContext ? tmp : null;
          var tmp_0;
          if (tmp0_elvis_lhs == null) {
            return size2;
          } else {
            tmp_0 = tmp0_elvis_lhs;
          }
          cur = tmp_0;
          var tmp1 = size2;
          size2 = tmp1 + 1 | 0;
        }
      }
      function contains_5($this, element) {
        return equals($this.get_1pi7hg_k$(element.get_key_18j28a_k$()), element);
      }
      function containsAll($this, context) {
        var cur = context;
        while (true) {
          if (!contains_5($this, cur.element_1))
            return false;
          var next = cur.left_1;
          if (next instanceof CombinedContext) {
            cur = next;
          } else {
            return contains_5($this, isInterface(next, Element2) ? next : THROW_CCE());
          }
        }
      }
      function writeReplace($this) {
        var n2 = size($this);
        var tmp$ret$0;
        tmp$ret$0 = fillArrayVal(Array(n2), null);
        var elements = tmp$ret$0;
        var index = { _v: 0 };
        $this.fold_6dbyow_k$(Unit_getInstance(), CombinedContext$writeReplace$lambda(elements, index));
        var tmp0_check = index._v === n2;
        if (!tmp0_check) {
          var tmp$ret$1;
          tmp$ret$1 = "Check failed.";
          var message = tmp$ret$1;
          throw IllegalStateException_init_$Create$_0(toString_1(message));
        }
        return new Serialized(isArray(elements) ? elements : THROW_CCE());
      }
      function Serialized(elements) {
        Companion_getInstance_0();
        this.elements_1 = elements;
      }
      Serialized.prototype.get_elements_vxwh8g_k$ = function() {
        return this.elements_1;
      };
      Serialized.$metadata$ = classMeta("Serialized", [Serializable]);
      function CombinedContext$toString$lambda(acc, element) {
        var tmp;
        var tmp$ret$0;
        tmp$ret$0 = charSequenceLength(acc) === 0;
        if (tmp$ret$0) {
          tmp = toString_1(element);
        } else {
          tmp = acc + ", " + element;
        }
        return tmp;
      }
      function CombinedContext$writeReplace$lambda($elements, $index) {
        return function(_anonymous_parameter_0__qggqh8, element) {
          var tmp0 = $index._v;
          $index._v = tmp0 + 1 | 0;
          $elements[tmp0] = element;
          return Unit_getInstance();
        };
      }
      function CombinedContext(left2, element) {
        this.left_1 = left2;
        this.element_1 = element;
      }
      CombinedContext.prototype.get_1pi7hg_k$ = function(key) {
        var cur = this;
        while (true) {
          var tmp0_safe_receiver = cur.element_1.get_1pi7hg_k$(key);
          if (tmp0_safe_receiver == null)
            null;
          else {
            var tmp$ret$0;
            return tmp0_safe_receiver;
          }
          var next = cur.left_1;
          if (next instanceof CombinedContext) {
            cur = next;
          } else {
            return next.get_1pi7hg_k$(key);
          }
        }
      };
      CombinedContext.prototype.fold_6dbyow_k$ = function(initial, operation) {
        return operation(this.left_1.fold_6dbyow_k$(initial, operation), this.element_1);
      };
      CombinedContext.prototype.minusKey_y21q55_k$ = function(key) {
        var tmp0_safe_receiver = this.element_1.get_1pi7hg_k$(key);
        if (tmp0_safe_receiver == null)
          null;
        else {
          var tmp$ret$0;
          return this.left_1;
        }
        var newLeft = this.left_1.minusKey_y21q55_k$(key);
        return newLeft === this.left_1 ? this : newLeft === EmptyCoroutineContext_getInstance() ? this.element_1 : new CombinedContext(newLeft, this.element_1);
      };
      CombinedContext.prototype.equals = function(other) {
        var tmp;
        if (this === other) {
          tmp = true;
        } else {
          var tmp_0;
          var tmp_1;
          if (other instanceof CombinedContext) {
            tmp_1 = size(other) === size(this);
          } else {
            tmp_1 = false;
          }
          if (tmp_1) {
            tmp_0 = containsAll(other, this);
          } else {
            tmp_0 = false;
          }
          tmp = tmp_0;
        }
        return tmp;
      };
      CombinedContext.prototype.hashCode = function() {
        return hashCode(this.left_1) + hashCode(this.element_1) | 0;
      };
      CombinedContext.prototype.toString = function() {
        return "[" + this.fold_6dbyow_k$("", CombinedContext$toString$lambda) + "]";
      };
      CombinedContext.$metadata$ = classMeta("CombinedContext", [CoroutineContext, Serializable]);
      function _get_safeCast__5d4zbz($this) {
        return $this.safeCast_1;
      }
      function _get_topmostKey__fyvvjw($this) {
        return $this.topmostKey_1;
      }
      function AbstractCoroutineContextKey(baseKey, safeCast) {
        this.safeCast_1 = safeCast;
        var tmp = this;
        var tmp_0;
        if (baseKey instanceof AbstractCoroutineContextKey) {
          tmp_0 = baseKey.topmostKey_1;
        } else {
          tmp_0 = baseKey;
        }
        tmp.topmostKey_1 = tmp_0;
      }
      AbstractCoroutineContextKey.prototype.tryCast_hqzvw1_k$ = function(element) {
        return this.safeCast_1(element);
      };
      AbstractCoroutineContextKey.prototype.isSubKey_5an70z_k$ = function(key) {
        return key === this ? true : this.topmostKey_1 === key;
      };
      AbstractCoroutineContextKey.$metadata$ = classMeta("AbstractCoroutineContextKey", [Key_0]);
      function get_COROUTINE_SUSPENDED() {
        return CoroutineSingletons_COROUTINE_SUSPENDED_getInstance();
      }
      var CoroutineSingletons_COROUTINE_SUSPENDED_instance;
      var CoroutineSingletons_UNDECIDED_instance;
      var CoroutineSingletons_RESUMED_instance;
      function values_1() {
        return [CoroutineSingletons_COROUTINE_SUSPENDED_getInstance(), CoroutineSingletons_UNDECIDED_getInstance(), CoroutineSingletons_RESUMED_getInstance()];
      }
      function valueOf_1(value) {
        switch (value) {
          case "COROUTINE_SUSPENDED":
            return CoroutineSingletons_COROUTINE_SUSPENDED_getInstance();
          case "UNDECIDED":
            return CoroutineSingletons_UNDECIDED_getInstance();
          case "RESUMED":
            return CoroutineSingletons_RESUMED_getInstance();
          default:
            CoroutineSingletons_initEntries();
            THROW_ISE();
            break;
        }
      }
      var CoroutineSingletons_entriesInitialized;
      function CoroutineSingletons_initEntries() {
        if (CoroutineSingletons_entriesInitialized)
          return Unit_getInstance();
        CoroutineSingletons_entriesInitialized = true;
        CoroutineSingletons_COROUTINE_SUSPENDED_instance = new CoroutineSingletons("COROUTINE_SUSPENDED", 0);
        CoroutineSingletons_UNDECIDED_instance = new CoroutineSingletons("UNDECIDED", 1);
        CoroutineSingletons_RESUMED_instance = new CoroutineSingletons("RESUMED", 2);
      }
      function CoroutineSingletons(name, ordinal) {
        Enum.call(this, name, ordinal);
      }
      CoroutineSingletons.$metadata$ = classMeta("CoroutineSingletons", void 0, void 0, void 0, void 0, Enum.prototype);
      function CoroutineSingletons_COROUTINE_SUSPENDED_getInstance() {
        CoroutineSingletons_initEntries();
        return CoroutineSingletons_COROUTINE_SUSPENDED_instance;
      }
      function CoroutineSingletons_UNDECIDED_getInstance() {
        CoroutineSingletons_initEntries();
        return CoroutineSingletons_UNDECIDED_instance;
      }
      function CoroutineSingletons_RESUMED_getInstance() {
        CoroutineSingletons_initEntries();
        return CoroutineSingletons_RESUMED_instance;
      }
      function and(_this__u8e3s4, other) {
        return toShort(_this__u8e3s4 & other);
      }
      function or(_this__u8e3s4, other) {
        return toShort(_this__u8e3s4 | other);
      }
      function xor2(_this__u8e3s4, other) {
        return toShort(_this__u8e3s4 ^ other);
      }
      function inv(_this__u8e3s4) {
        return toShort(~_this__u8e3s4);
      }
      function and_0(_this__u8e3s4, other) {
        return toByte(_this__u8e3s4 & other);
      }
      function or_0(_this__u8e3s4, other) {
        return toByte(_this__u8e3s4 | other);
      }
      function xor_0(_this__u8e3s4, other) {
        return toByte(_this__u8e3s4 ^ other);
      }
      function inv_0(_this__u8e3s4) {
        return toByte(~_this__u8e3s4);
      }
      function ExperimentalTypeInference() {
      }
      ExperimentalTypeInference.prototype.equals = function(other) {
        if (!(other instanceof ExperimentalTypeInference))
          return false;
        var tmp0_other_with_cast = other instanceof ExperimentalTypeInference ? other : THROW_CCE();
        return true;
      };
      ExperimentalTypeInference.prototype.hashCode = function() {
        return 0;
      };
      ExperimentalTypeInference.prototype.toString = function() {
        return "@kotlin.experimental.ExperimentalTypeInference()";
      };
      ExperimentalTypeInference.$metadata$ = classMeta("ExperimentalTypeInference", [Annotation]);
      function InlineOnly() {
      }
      InlineOnly.prototype.equals = function(other) {
        if (!(other instanceof InlineOnly))
          return false;
        var tmp0_other_with_cast = other instanceof InlineOnly ? other : THROW_CCE();
        return true;
      };
      InlineOnly.prototype.hashCode = function() {
        return 0;
      };
      InlineOnly.prototype.toString = function() {
        return "@kotlin.internal.InlineOnly()";
      };
      InlineOnly.$metadata$ = classMeta("InlineOnly", [Annotation]);
      function LowPriorityInOverloadResolution() {
      }
      LowPriorityInOverloadResolution.prototype.equals = function(other) {
        if (!(other instanceof LowPriorityInOverloadResolution))
          return false;
        var tmp0_other_with_cast = other instanceof LowPriorityInOverloadResolution ? other : THROW_CCE();
        return true;
      };
      LowPriorityInOverloadResolution.prototype.hashCode = function() {
        return 0;
      };
      LowPriorityInOverloadResolution.prototype.toString = function() {
        return "@kotlin.internal.LowPriorityInOverloadResolution()";
      };
      LowPriorityInOverloadResolution.$metadata$ = classMeta("LowPriorityInOverloadResolution", [Annotation]);
      function NoInfer() {
      }
      NoInfer.prototype.equals = function(other) {
        if (!(other instanceof NoInfer))
          return false;
        var tmp0_other_with_cast = other instanceof NoInfer ? other : THROW_CCE();
        return true;
      };
      NoInfer.prototype.hashCode = function() {
        return 0;
      };
      NoInfer.prototype.toString = function() {
        return "@kotlin.internal.NoInfer()";
      };
      NoInfer.$metadata$ = classMeta("NoInfer", [Annotation]);
      function DynamicExtension() {
      }
      DynamicExtension.prototype.equals = function(other) {
        if (!(other instanceof DynamicExtension))
          return false;
        var tmp0_other_with_cast = other instanceof DynamicExtension ? other : THROW_CCE();
        return true;
      };
      DynamicExtension.prototype.hashCode = function() {
        return 0;
      };
      DynamicExtension.prototype.toString = function() {
        return "@kotlin.internal.DynamicExtension()";
      };
      DynamicExtension.$metadata$ = classMeta("DynamicExtension", [Annotation]);
      function ContractsDsl() {
      }
      ContractsDsl.prototype.equals = function(other) {
        if (!(other instanceof ContractsDsl))
          return false;
        var tmp0_other_with_cast = other instanceof ContractsDsl ? other : THROW_CCE();
        return true;
      };
      ContractsDsl.prototype.hashCode = function() {
        return 0;
      };
      ContractsDsl.prototype.toString = function() {
        return "@kotlin.internal.ContractsDsl()";
      };
      ContractsDsl.$metadata$ = classMeta("ContractsDsl", [Annotation]);
      function OnlyInputTypes() {
      }
      OnlyInputTypes.prototype.equals = function(other) {
        if (!(other instanceof OnlyInputTypes))
          return false;
        var tmp0_other_with_cast = other instanceof OnlyInputTypes ? other : THROW_CCE();
        return true;
      };
      OnlyInputTypes.prototype.hashCode = function() {
        return 0;
      };
      OnlyInputTypes.prototype.toString = function() {
        return "@kotlin.internal.OnlyInputTypes()";
      };
      OnlyInputTypes.$metadata$ = classMeta("OnlyInputTypes", [Annotation]);
      function getProgressionLastElement(start2, end, step) {
        var tmp;
        if (step > 0) {
          tmp = start2 >= end ? end : end - differenceModulo(end, start2, step) | 0;
        } else if (step < 0) {
          tmp = start2 <= end ? end : end + differenceModulo(start2, end, -step | 0) | 0;
        } else {
          throw IllegalArgumentException_init_$Create$_0("Step is zero.");
        }
        return tmp;
      }
      function getProgressionLastElement_0(start2, end, step) {
        var tmp;
        if (step.compareTo_n4fqi2_k$(new Long(0, 0)) > 0) {
          tmp = start2.compareTo_n4fqi2_k$(end) >= 0 ? end : end.minus_llf5ei_k$(differenceModulo_0(end, start2, step));
        } else if (step.compareTo_n4fqi2_k$(new Long(0, 0)) < 0) {
          tmp = start2.compareTo_n4fqi2_k$(end) <= 0 ? end : end.plus_u6jwas_k$(differenceModulo_0(start2, end, step.unaryMinus_6uz0qp_k$()));
        } else {
          throw IllegalArgumentException_init_$Create$_0("Step is zero.");
        }
        return tmp;
      }
      function differenceModulo(a, b, c) {
        return mod(mod(a, c) - mod(b, c) | 0, c);
      }
      function differenceModulo_0(a, b, c) {
        return mod_0(mod_0(a, c).minus_llf5ei_k$(mod_0(b, c)), c);
      }
      function mod(a, b) {
        var mod2 = a % b | 0;
        return mod2 >= 0 ? mod2 : mod2 + b | 0;
      }
      function mod_0(a, b) {
        var mod2 = a.rem_9rbcjo_k$(b);
        return mod2.compareTo_n4fqi2_k$(new Long(0, 0)) >= 0 ? mod2 : mod2.plus_u6jwas_k$(b);
      }
      function _get_serialVersionUID__fhggm9_2($this) {
        return $this.serialVersionUID_1;
      }
      function readResolve_2($this) {
        return Default_getInstance();
      }
      function _get_defaultRandom__d0xjir($this) {
        return $this.defaultRandom_1;
      }
      function Serialized_0() {
        Serialized_instance = this;
        this.serialVersionUID_1 = new Long(0, 0);
      }
      Serialized_0.$metadata$ = objectMeta("Serialized", [Serializable]);
      var Serialized_instance;
      function Serialized_getInstance() {
        if (Serialized_instance == null)
          new Serialized_0();
        return Serialized_instance;
      }
      function writeReplace_0($this) {
        return Serialized_getInstance();
      }
      function Default() {
        Default_instance = this;
        Random.call(this);
        this.defaultRandom_1 = defaultPlatformRandom();
      }
      Default.prototype.nextBits_30zi6g_k$ = function(bitCount) {
        return this.defaultRandom_1.nextBits_30zi6g_k$(bitCount);
      };
      Default.prototype.nextInt_ujorgc_k$ = function() {
        return this.defaultRandom_1.nextInt_ujorgc_k$();
      };
      Default.prototype.nextInt_8t3gcb_k$ = function(until2) {
        return this.defaultRandom_1.nextInt_8t3gcb_k$(until2);
      };
      Default.prototype.nextInt_6ppfmk_k$ = function(from, until2) {
        return this.defaultRandom_1.nextInt_6ppfmk_k$(from, until2);
      };
      Default.prototype.nextLong_njwv0v_k$ = function() {
        return this.defaultRandom_1.nextLong_njwv0v_k$();
      };
      Default.prototype.nextLong_gpvfev_k$ = function(until2) {
        return this.defaultRandom_1.nextLong_gpvfev_k$(until2);
      };
      Default.prototype.nextLong_8yy44j_k$ = function(from, until2) {
        return this.defaultRandom_1.nextLong_8yy44j_k$(from, until2);
      };
      Default.prototype.nextBoolean_nfdk1h_k$ = function() {
        return this.defaultRandom_1.nextBoolean_nfdk1h_k$();
      };
      Default.prototype.nextDouble_s2xvfg_k$ = function() {
        return this.defaultRandom_1.nextDouble_s2xvfg_k$();
      };
      Default.prototype.nextDouble_b5661v_k$ = function(until2) {
        return this.defaultRandom_1.nextDouble_b5661v_k$(until2);
      };
      Default.prototype.nextDouble_2cs2ou_k$ = function(from, until2) {
        return this.defaultRandom_1.nextDouble_2cs2ou_k$(from, until2);
      };
      Default.prototype.nextFloat_jqti5l_k$ = function() {
        return this.defaultRandom_1.nextFloat_jqti5l_k$();
      };
      Default.prototype.nextBytes_7yvat1_k$ = function(array3) {
        return this.defaultRandom_1.nextBytes_7yvat1_k$(array3);
      };
      Default.prototype.nextBytes_oxmcdz_k$ = function(size2) {
        return this.defaultRandom_1.nextBytes_oxmcdz_k$(size2);
      };
      Default.prototype.nextBytes_zhahm3_k$ = function(array3, fromIndex, toIndex) {
        return this.defaultRandom_1.nextBytes_zhahm3_k$(array3, fromIndex, toIndex);
      };
      Default.$metadata$ = objectMeta("Default", [Serializable], void 0, void 0, void 0, Random.prototype);
      var Default_instance;
      function Default_getInstance() {
        if (Default_instance == null)
          new Default();
        return Default_instance;
      }
      function Random() {
        Default_getInstance();
      }
      Random.prototype.nextInt_ujorgc_k$ = function() {
        return this.nextBits_30zi6g_k$(32);
      };
      Random.prototype.nextInt_8t3gcb_k$ = function(until2) {
        return this.nextInt_6ppfmk_k$(0, until2);
      };
      Random.prototype.nextInt_6ppfmk_k$ = function(from, until2) {
        checkRangeBounds(from, until2);
        var n2 = until2 - from | 0;
        if (n2 > 0 ? true : n2 === IntCompanionObject_getInstance().MIN_VALUE_1) {
          var tmp;
          if ((n2 & (-n2 | 0)) === n2) {
            var bitCount = fastLog2(n2);
            tmp = this.nextBits_30zi6g_k$(bitCount);
          } else {
            var v;
            do {
              var bits = this.nextInt_ujorgc_k$() >>> 1 | 0;
              v = bits % n2 | 0;
            } while (((bits - v | 0) + (n2 - 1 | 0) | 0) < 0);
            tmp = v;
          }
          var rnd = tmp;
          return from + rnd | 0;
        } else {
          while (true) {
            var rnd_0 = this.nextInt_ujorgc_k$();
            if (from <= rnd_0 ? rnd_0 < until2 : false)
              return rnd_0;
          }
        }
      };
      Random.prototype.nextLong_njwv0v_k$ = function() {
        var tmp$ret$0;
        var tmp0_plus = toLong(this.nextInt_ujorgc_k$()).shl_po5ip6_k$(32);
        var tmp1_plus = this.nextInt_ujorgc_k$();
        tmp$ret$0 = tmp0_plus.plus_u6jwas_k$(toLong(tmp1_plus));
        return tmp$ret$0;
      };
      Random.prototype.nextLong_gpvfev_k$ = function(until2) {
        return this.nextLong_8yy44j_k$(new Long(0, 0), until2);
      };
      Random.prototype.nextLong_8yy44j_k$ = function(from, until2) {
        checkRangeBounds_0(from, until2);
        var n2 = until2.minus_llf5ei_k$(from);
        if (n2.compareTo_n4fqi2_k$(new Long(0, 0)) > 0) {
          var rnd;
          if (n2.and_jhajnj_k$(n2.unaryMinus_6uz0qp_k$()).equals(n2)) {
            var nLow = n2.toInt_1tsl84_k$();
            var nHigh = n2.ushr_rr8rvr_k$(32).toInt_1tsl84_k$();
            var tmp;
            if (!(nLow === 0)) {
              var bitCount = fastLog2(nLow);
              tmp = toLong(this.nextBits_30zi6g_k$(bitCount)).and_jhajnj_k$(new Long(-1, 0));
            } else if (nHigh === 1) {
              tmp = toLong(this.nextInt_ujorgc_k$()).and_jhajnj_k$(new Long(-1, 0));
            } else {
              var bitCount_0 = fastLog2(nHigh);
              tmp = toLong(this.nextBits_30zi6g_k$(bitCount_0)).shl_po5ip6_k$(32).plus_u6jwas_k$(toLong(this.nextInt_ujorgc_k$()).and_jhajnj_k$(new Long(-1, 0)));
            }
            rnd = tmp;
          } else {
            var v;
            $l$1: do {
              $l$0: do {
                var bits = this.nextLong_njwv0v_k$().ushr_rr8rvr_k$(1);
                v = bits.rem_9rbcjo_k$(n2);
              } while (false);
              var tmp_0 = bits.minus_llf5ei_k$(v);
              var tmp$ret$0;
              tmp$ret$0 = n2.minus_llf5ei_k$(new Long(1, 0));
            } while (tmp_0.plus_u6jwas_k$(tmp$ret$0).compareTo_n4fqi2_k$(new Long(0, 0)) < 0);
            rnd = v;
          }
          return from.plus_u6jwas_k$(rnd);
        } else {
          while (true) {
            var rnd_0 = this.nextLong_njwv0v_k$();
            if (from.compareTo_n4fqi2_k$(rnd_0) <= 0 ? rnd_0.compareTo_n4fqi2_k$(until2) < 0 : false)
              return rnd_0;
          }
        }
      };
      Random.prototype.nextBoolean_nfdk1h_k$ = function() {
        return !(this.nextBits_30zi6g_k$(1) === 0);
      };
      Random.prototype.nextDouble_s2xvfg_k$ = function() {
        return doubleFromParts(this.nextBits_30zi6g_k$(26), this.nextBits_30zi6g_k$(27));
      };
      Random.prototype.nextDouble_b5661v_k$ = function(until2) {
        return this.nextDouble_2cs2ou_k$(0, until2);
      };
      Random.prototype.nextDouble_2cs2ou_k$ = function(from, until2) {
        checkRangeBounds_1(from, until2);
        var size2 = until2 - from;
        var tmp;
        if ((isInfinite(size2) ? isFinite2(from) : false) ? isFinite2(until2) : false) {
          var r1 = this.nextDouble_s2xvfg_k$() * (until2 / 2 - from / 2);
          tmp = from + r1 + r1;
        } else {
          tmp = from + this.nextDouble_s2xvfg_k$() * size2;
        }
        var r = tmp;
        return r >= until2 ? nextDown(until2) : r;
      };
      Random.prototype.nextFloat_jqti5l_k$ = function() {
        return this.nextBits_30zi6g_k$(24) / 16777216;
      };
      Random.prototype.nextBytes_zhahm3_k$ = function(array3, fromIndex, toIndex) {
        var tmp0_require = (0 <= fromIndex ? fromIndex <= array3.length : false) ? 0 <= toIndex ? toIndex <= array3.length : false : false;
        if (!tmp0_require) {
          var tmp$ret$0;
          tmp$ret$0 = "fromIndex (" + fromIndex + ") or toIndex (" + toIndex + ") are out of range: 0.." + array3.length + ".";
          var message = tmp$ret$0;
          throw IllegalArgumentException_init_$Create$_0(toString_1(message));
        }
        var tmp1_require = fromIndex <= toIndex;
        if (!tmp1_require) {
          var tmp$ret$1;
          tmp$ret$1 = "fromIndex (" + fromIndex + ") must be not greater than toIndex (" + toIndex + ").";
          var message_0 = tmp$ret$1;
          throw IllegalArgumentException_init_$Create$_0(toString_1(message_0));
        }
        var steps = (toIndex - fromIndex | 0) / 4 | 0;
        var position = fromIndex;
        var inductionVariable = 0;
        if (inductionVariable < steps)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var v = this.nextInt_ujorgc_k$();
            array3[position] = toByte(v);
            array3[position + 1 | 0] = toByte(v >>> 8 | 0);
            array3[position + 2 | 0] = toByte(v >>> 16 | 0);
            array3[position + 3 | 0] = toByte(v >>> 24 | 0);
            position = position + 4 | 0;
          } while (inductionVariable < steps);
        var remainder = toIndex - position | 0;
        var vr = this.nextBits_30zi6g_k$(imul(remainder, 8));
        var inductionVariable_0 = 0;
        if (inductionVariable_0 < remainder)
          do {
            var i = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            array3[position + i | 0] = toByte(vr >>> imul(i, 8) | 0);
          } while (inductionVariable_0 < remainder);
        return array3;
      };
      Random.prototype.nextBytes$default_rw0xws_k$ = function(array3, fromIndex, toIndex, $mask0, $handler) {
        if (!(($mask0 & 2) === 0))
          fromIndex = 0;
        if (!(($mask0 & 4) === 0))
          toIndex = array3.length;
        return $handler == null ? this.nextBytes_zhahm3_k$(array3, fromIndex, toIndex) : $handler(array3, fromIndex, toIndex);
      };
      Random.prototype.nextBytes_7yvat1_k$ = function(array3) {
        return this.nextBytes_zhahm3_k$(array3, 0, array3.length);
      };
      Random.prototype.nextBytes_oxmcdz_k$ = function(size2) {
        return this.nextBytes_7yvat1_k$(new Int8Array(size2));
      };
      Random.$metadata$ = classMeta("Random");
      function checkRangeBounds(from, until2) {
        var tmp0_require = until2 > from;
        var tmp;
        if (!tmp0_require) {
          var tmp$ret$0;
          tmp$ret$0 = boundsErrorMessage(from, until2);
          var message = tmp$ret$0;
          throw IllegalArgumentException_init_$Create$_0(toString_1(message));
        }
        return tmp;
      }
      function fastLog2(value) {
        var tmp$ret$0;
        tmp$ret$0 = clz32(value);
        return 31 - tmp$ret$0 | 0;
      }
      function checkRangeBounds_0(from, until2) {
        var tmp0_require = until2.compareTo_n4fqi2_k$(from) > 0;
        var tmp;
        if (!tmp0_require) {
          var tmp$ret$0;
          tmp$ret$0 = boundsErrorMessage(from, until2);
          var message = tmp$ret$0;
          throw IllegalArgumentException_init_$Create$_0(toString_1(message));
        }
        return tmp;
      }
      function checkRangeBounds_1(from, until2) {
        var tmp0_require = until2 > from;
        var tmp;
        if (!tmp0_require) {
          var tmp$ret$0;
          tmp$ret$0 = boundsErrorMessage(from, until2);
          var message = tmp$ret$0;
          throw IllegalArgumentException_init_$Create$_0(toString_1(message));
        }
        return tmp;
      }
      function boundsErrorMessage(from, until2) {
        return "Random range is empty: [" + toString_1(from) + ", " + toString_1(until2) + ").";
      }
      function Random_0(seed) {
        return XorWowRandom_init_$Create$(seed, seed >> 31);
      }
      function takeUpperBits(_this__u8e3s4, bitCount) {
        return (_this__u8e3s4 >>> (32 - bitCount | 0) | 0) & (-bitCount | 0) >> 31;
      }
      function _get_serialVersionUID__fhggm9_3($this) {
        return $this.serialVersionUID_1;
      }
      function _set_x__db55ql($this, _set____db54di) {
        $this.x_1 = _set____db54di;
      }
      function _get_x__7mlp09($this) {
        return $this.x_1;
      }
      function _set_y__db55rg($this, _set____db54di) {
        $this.y_1 = _set____db54di;
      }
      function _get_y__7mlp14($this) {
        return $this.y_1;
      }
      function _set_z__db55sb($this, _set____db54di) {
        $this.z_1 = _set____db54di;
      }
      function _get_z__7mlp1z($this) {
        return $this.z_1;
      }
      function _set_w__db55pq($this, _set____db54di) {
        $this.w_1 = _set____db54di;
      }
      function _get_w__7mloze($this) {
        return $this.w_1;
      }
      function _set_v__db55ov($this, _set____db54di) {
        $this.v_1 = _set____db54di;
      }
      function _get_v__7mloyj($this) {
        return $this.v_1;
      }
      function _set_addend__hcd0al($this, _set____db54di) {
        $this.addend_1 = _set____db54di;
      }
      function _get_addend__it3kxd($this) {
        return $this.addend_1;
      }
      function XorWowRandom_init_$Init$(seed1, seed2, $this) {
        XorWowRandom.call($this, seed1, seed2, 0, 0, ~seed1, seed1 << 10 ^ (seed2 >>> 4 | 0));
        return $this;
      }
      function XorWowRandom_init_$Create$(seed1, seed2) {
        return XorWowRandom_init_$Init$(seed1, seed2, Object.create(XorWowRandom.prototype));
      }
      function Companion_1() {
        Companion_instance_1 = this;
        this.serialVersionUID_1 = new Long(0, 0);
      }
      Companion_1.$metadata$ = objectMeta("Companion");
      var Companion_instance_1;
      function Companion_getInstance_1() {
        if (Companion_instance_1 == null)
          new Companion_1();
        return Companion_instance_1;
      }
      function XorWowRandom(x2, y2, z2, w, v, addend) {
        Companion_getInstance_1();
        Random.call(this);
        this.x_1 = x2;
        this.y_1 = y2;
        this.z_1 = z2;
        this.w_1 = w;
        this.v_1 = v;
        this.addend_1 = addend;
        var tmp0_require = !((this.x_1 | this.y_1 | this.z_1 | this.w_1 | this.v_1) === 0);
        if (!tmp0_require) {
          var tmp$ret$0;
          tmp$ret$0 = "Initial state must have at least one non-zero element.";
          var message = tmp$ret$0;
          throw IllegalArgumentException_init_$Create$_0(toString_1(message));
        }
        var inductionVariable = 0;
        if (inductionVariable < 64)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            this.nextInt_ujorgc_k$();
          } while (inductionVariable < 64);
      }
      XorWowRandom.prototype.nextInt_ujorgc_k$ = function() {
        var t = this.x_1;
        t = t ^ (t >>> 2 | 0);
        this.x_1 = this.y_1;
        this.y_1 = this.z_1;
        this.z_1 = this.w_1;
        var v0 = this.v_1;
        this.w_1 = v0;
        t = t ^ t << 1 ^ v0 ^ v0 << 4;
        this.v_1 = t;
        var tmp0_this = this;
        tmp0_this.addend_1 = tmp0_this.addend_1 + 362437 | 0;
        return t + this.addend_1 | 0;
      };
      XorWowRandom.prototype.nextBits_30zi6g_k$ = function(bitCount) {
        return takeUpperBits(this.nextInt_ujorgc_k$(), bitCount);
      };
      XorWowRandom.$metadata$ = classMeta("XorWowRandom", [Serializable], void 0, void 0, void 0, Random.prototype);
      function Companion_2() {
        Companion_instance_2 = this;
        this.EMPTY_1 = new IntRange(1, 0);
      }
      Companion_2.prototype.get_EMPTY_i8q41w_k$ = function() {
        return this.EMPTY_1;
      };
      Companion_2.$metadata$ = objectMeta("Companion");
      var Companion_instance_2;
      function Companion_getInstance_2() {
        if (Companion_instance_2 == null)
          new Companion_2();
        return Companion_instance_2;
      }
      function IntRange(start2, endInclusive) {
        Companion_getInstance_2();
        IntProgression.call(this, start2, endInclusive, 1);
      }
      IntRange.prototype.get_start_iypx6h_k$ = function() {
        return this.first_1;
      };
      IntRange.prototype.get_endInclusive_r07xpi_k$ = function() {
        return this.last_1;
      };
      IntRange.prototype.get_endExclusive_pmwm6k_k$ = function() {
        if (this.last_1 === IntCompanionObject_getInstance().MAX_VALUE_1) {
          throw IllegalStateException_init_$Create$_0("Cannot return the exclusive upper bound of a range that includes MAX_VALUE.");
        }
        return this.last_1 + 1 | 0;
      };
      IntRange.prototype.contains_1pg60y_k$ = function(value) {
        return this.first_1 <= value ? value <= this.last_1 : false;
      };
      IntRange.prototype.contains_2ehdtg_k$ = function(value) {
        return this.contains_1pg60y_k$(typeof value === "number" ? value : THROW_CCE());
      };
      IntRange.prototype.isEmpty_y1axqb_k$ = function() {
        return this.first_1 > this.last_1;
      };
      IntRange.prototype.equals = function(other) {
        var tmp;
        if (other instanceof IntRange) {
          tmp = (this.isEmpty_y1axqb_k$() ? other.isEmpty_y1axqb_k$() : false) ? true : this.first_1 === other.first_1 ? this.last_1 === other.last_1 : false;
        } else {
          tmp = false;
        }
        return tmp;
      };
      IntRange.prototype.hashCode = function() {
        return this.isEmpty_y1axqb_k$() ? -1 : imul(31, this.first_1) + this.last_1 | 0;
      };
      IntRange.prototype.toString = function() {
        return "" + this.first_1 + ".." + this.last_1;
      };
      IntRange.$metadata$ = classMeta("IntRange", [ClosedRange, OpenEndRange], void 0, void 0, void 0, IntProgression.prototype);
      function Companion_3() {
        Companion_instance_3 = this;
        this.EMPTY_1 = new CharRange(_Char___init__impl__6a9atx(1), _Char___init__impl__6a9atx(0));
      }
      Companion_3.prototype.get_EMPTY_i8q41w_k$ = function() {
        return this.EMPTY_1;
      };
      Companion_3.$metadata$ = objectMeta("Companion");
      var Companion_instance_3;
      function Companion_getInstance_3() {
        if (Companion_instance_3 == null)
          new Companion_3();
        return Companion_instance_3;
      }
      function CharRange(start2, endInclusive) {
        Companion_getInstance_3();
        CharProgression.call(this, start2, endInclusive, 1);
      }
      CharRange.prototype.get_start_qj1pkq_k$ = function() {
        return this.first_1;
      };
      CharRange.prototype.get_start_iypx6h_k$ = function() {
        return new Char_0(this.get_start_qj1pkq_k$());
      };
      CharRange.prototype.get_endInclusive_oogq1x_k$ = function() {
        return this.last_1;
      };
      CharRange.prototype.get_endInclusive_r07xpi_k$ = function() {
        return new Char_0(this.get_endInclusive_oogq1x_k$());
      };
      CharRange.prototype.get_endExclusive_umcki5_k$ = function() {
        var tmp = new Char_0(this.last_1);
        Companion_getInstance_18();
        if (equals(tmp, new Char_0(_Char___init__impl__6a9atx(65535)))) {
          throw IllegalStateException_init_$Create$_0("Cannot return the exclusive upper bound of a range that includes MAX_VALUE.");
        }
        return Char__plus_impl_qi7pgj(this.last_1, 1);
      };
      CharRange.prototype.get_endExclusive_pmwm6k_k$ = function() {
        return new Char_0(this.get_endExclusive_umcki5_k$());
      };
      CharRange.prototype.contains_i4atwd_k$ = function(value) {
        return Char__compareTo_impl_ypi4mb(this.first_1, value) <= 0 ? Char__compareTo_impl_ypi4mb(value, this.last_1) <= 0 : false;
      };
      CharRange.prototype.contains_2ehdtg_k$ = function(value) {
        return this.contains_i4atwd_k$(value instanceof Char_0 ? value.value_1 : THROW_CCE());
      };
      CharRange.prototype.isEmpty_y1axqb_k$ = function() {
        return Char__compareTo_impl_ypi4mb(this.first_1, this.last_1) > 0;
      };
      CharRange.prototype.equals = function(other) {
        var tmp;
        if (other instanceof CharRange) {
          tmp = (this.isEmpty_y1axqb_k$() ? other.isEmpty_y1axqb_k$() : false) ? true : equals(new Char_0(this.first_1), new Char_0(other.first_1)) ? equals(new Char_0(this.last_1), new Char_0(other.last_1)) : false;
        } else {
          tmp = false;
        }
        return tmp;
      };
      CharRange.prototype.hashCode = function() {
        var tmp;
        if (this.isEmpty_y1axqb_k$()) {
          tmp = -1;
        } else {
          var tmp$ret$0;
          var tmp0__get_code__88qj9g = this.first_1;
          tmp$ret$0 = Char__toInt_impl_vasixd(tmp0__get_code__88qj9g);
          var tmp_0 = imul(31, tmp$ret$0);
          var tmp$ret$1;
          var tmp1__get_code__adl84j = this.last_1;
          tmp$ret$1 = Char__toInt_impl_vasixd(tmp1__get_code__adl84j);
          tmp = tmp_0 + tmp$ret$1 | 0;
        }
        return tmp;
      };
      CharRange.prototype.toString = function() {
        return "" + new Char_0(this.first_1) + ".." + new Char_0(this.last_1);
      };
      CharRange.$metadata$ = classMeta("CharRange", [ClosedRange, OpenEndRange], void 0, void 0, void 0, CharProgression.prototype);
      function Companion_4() {
        Companion_instance_4 = this;
        this.EMPTY_1 = new LongRange(new Long(1, 0), new Long(0, 0));
      }
      Companion_4.prototype.get_EMPTY_i8q41w_k$ = function() {
        return this.EMPTY_1;
      };
      Companion_4.$metadata$ = objectMeta("Companion");
      var Companion_instance_4;
      function Companion_getInstance_4() {
        if (Companion_instance_4 == null)
          new Companion_4();
        return Companion_instance_4;
      }
      function LongRange(start2, endInclusive) {
        Companion_getInstance_4();
        LongProgression.call(this, start2, endInclusive, new Long(1, 0));
      }
      LongRange.prototype.get_start_iypx6h_k$ = function() {
        return this.first_1;
      };
      LongRange.prototype.get_endInclusive_r07xpi_k$ = function() {
        return this.last_1;
      };
      LongRange.prototype.get_endExclusive_pmwm6k_k$ = function() {
        Companion_getInstance_20();
        if (this.last_1.equals(new Long(-1, 2147483647))) {
          throw IllegalStateException_init_$Create$_0("Cannot return the exclusive upper bound of a range that includes MAX_VALUE.");
        }
        var tmp$ret$0;
        var tmp0_plus = this.last_1;
        tmp$ret$0 = tmp0_plus.plus_u6jwas_k$(new Long(1, 0));
        return tmp$ret$0;
      };
      LongRange.prototype.contains_i44xiv_k$ = function(value) {
        return this.first_1.compareTo_n4fqi2_k$(value) <= 0 ? value.compareTo_n4fqi2_k$(this.last_1) <= 0 : false;
      };
      LongRange.prototype.contains_2ehdtg_k$ = function(value) {
        return this.contains_i44xiv_k$(value instanceof Long ? value : THROW_CCE());
      };
      LongRange.prototype.isEmpty_y1axqb_k$ = function() {
        return this.first_1.compareTo_n4fqi2_k$(this.last_1) > 0;
      };
      LongRange.prototype.equals = function(other) {
        var tmp;
        if (other instanceof LongRange) {
          tmp = (this.isEmpty_y1axqb_k$() ? other.isEmpty_y1axqb_k$() : false) ? true : this.first_1.equals(other.first_1) ? this.last_1.equals(other.last_1) : false;
        } else {
          tmp = false;
        }
        return tmp;
      };
      LongRange.prototype.hashCode = function() {
        return this.isEmpty_y1axqb_k$() ? -1 : numberToLong(31).times_2zfqpc_k$(this.first_1.xor_jjua9n_k$(this.first_1.ushr_rr8rvr_k$(32))).plus_u6jwas_k$(this.last_1.xor_jjua9n_k$(this.last_1.ushr_rr8rvr_k$(32))).toInt_1tsl84_k$();
      };
      LongRange.prototype.toString = function() {
        return toString_1(this.first_1) + ".." + toString_1(this.last_1);
      };
      LongRange.$metadata$ = classMeta("LongRange", [ClosedRange, OpenEndRange], void 0, void 0, void 0, LongProgression.prototype);
      function _get_finalElement__gc6m3p($this) {
        return $this.finalElement_1;
      }
      function _set_hasNext__86v2bs($this, _set____db54di) {
        $this.hasNext_1 = _set____db54di;
      }
      function _get_hasNext__xt3cos($this) {
        return $this.hasNext_1;
      }
      function _set_next__9r2xms($this, _set____db54di) {
        $this.next_1 = _set____db54di;
      }
      function _get_next__daux88($this) {
        return $this.next_1;
      }
      function IntProgressionIterator(first, last, step) {
        IntIterator.call(this);
        this.step_1 = step;
        this.finalElement_1 = last;
        this.hasNext_1 = this.step_1 > 0 ? first <= last : first >= last;
        this.next_1 = this.hasNext_1 ? first : this.finalElement_1;
      }
      IntProgressionIterator.prototype.get_step_woujh1_k$ = function() {
        return this.step_1;
      };
      IntProgressionIterator.prototype.hasNext_bitz1p_k$ = function() {
        return this.hasNext_1;
      };
      IntProgressionIterator.prototype.nextInt_ujorgc_k$ = function() {
        var value = this.next_1;
        if (value === this.finalElement_1) {
          if (!this.hasNext_1)
            throw NoSuchElementException_init_$Create$();
          this.hasNext_1 = false;
        } else {
          var tmp0_this = this;
          tmp0_this.next_1 = tmp0_this.next_1 + this.step_1 | 0;
        }
        return value;
      };
      IntProgressionIterator.$metadata$ = classMeta("IntProgressionIterator", void 0, void 0, void 0, void 0, IntIterator.prototype);
      function _get_finalElement__gc6m3p_0($this) {
        return $this.finalElement_1;
      }
      function _set_hasNext__86v2bs_0($this, _set____db54di) {
        $this.hasNext_1 = _set____db54di;
      }
      function _get_hasNext__xt3cos_0($this) {
        return $this.hasNext_1;
      }
      function _set_next__9r2xms_0($this, _set____db54di) {
        $this.next_1 = _set____db54di;
      }
      function _get_next__daux88_0($this) {
        return $this.next_1;
      }
      function CharProgressionIterator(first, last, step) {
        CharIterator.call(this);
        this.step_1 = step;
        var tmp = this;
        var tmp$ret$0;
        tmp$ret$0 = Char__toInt_impl_vasixd(last);
        tmp.finalElement_1 = tmp$ret$0;
        this.hasNext_1 = this.step_1 > 0 ? Char__compareTo_impl_ypi4mb(first, last) <= 0 : Char__compareTo_impl_ypi4mb(first, last) >= 0;
        var tmp_0 = this;
        var tmp_1;
        if (this.hasNext_1) {
          var tmp$ret$1;
          tmp$ret$1 = Char__toInt_impl_vasixd(first);
          tmp_1 = tmp$ret$1;
        } else {
          tmp_1 = this.finalElement_1;
        }
        tmp_0.next_1 = tmp_1;
      }
      CharProgressionIterator.prototype.get_step_woujh1_k$ = function() {
        return this.step_1;
      };
      CharProgressionIterator.prototype.hasNext_bitz1p_k$ = function() {
        return this.hasNext_1;
      };
      CharProgressionIterator.prototype.nextChar_yv3rl6_k$ = function() {
        var value = this.next_1;
        if (value === this.finalElement_1) {
          if (!this.hasNext_1)
            throw NoSuchElementException_init_$Create$();
          this.hasNext_1 = false;
        } else {
          var tmp0_this = this;
          tmp0_this.next_1 = tmp0_this.next_1 + this.step_1 | 0;
        }
        return numberToChar(value);
      };
      CharProgressionIterator.$metadata$ = classMeta("CharProgressionIterator", void 0, void 0, void 0, void 0, CharIterator.prototype);
      function _get_finalElement__gc6m3p_1($this) {
        return $this.finalElement_1;
      }
      function _set_hasNext__86v2bs_1($this, _set____db54di) {
        $this.hasNext_1 = _set____db54di;
      }
      function _get_hasNext__xt3cos_1($this) {
        return $this.hasNext_1;
      }
      function _set_next__9r2xms_1($this, _set____db54di) {
        $this.next_1 = _set____db54di;
      }
      function _get_next__daux88_1($this) {
        return $this.next_1;
      }
      function LongProgressionIterator(first, last, step) {
        LongIterator.call(this);
        this.step_1 = step;
        this.finalElement_1 = last;
        this.hasNext_1 = this.step_1.compareTo_n4fqi2_k$(new Long(0, 0)) > 0 ? first.compareTo_n4fqi2_k$(last) <= 0 : first.compareTo_n4fqi2_k$(last) >= 0;
        this.next_1 = this.hasNext_1 ? first : this.finalElement_1;
      }
      LongProgressionIterator.prototype.get_step_woujh1_k$ = function() {
        return this.step_1;
      };
      LongProgressionIterator.prototype.hasNext_bitz1p_k$ = function() {
        return this.hasNext_1;
      };
      LongProgressionIterator.prototype.nextLong_njwv0v_k$ = function() {
        var value = this.next_1;
        if (value.equals(this.finalElement_1)) {
          if (!this.hasNext_1)
            throw NoSuchElementException_init_$Create$();
          this.hasNext_1 = false;
        } else {
          var tmp0_this = this;
          tmp0_this.next_1 = tmp0_this.next_1.plus_u6jwas_k$(this.step_1);
        }
        return value;
      };
      LongProgressionIterator.$metadata$ = classMeta("LongProgressionIterator", void 0, void 0, void 0, void 0, LongIterator.prototype);
      function Companion_5() {
        Companion_instance_5 = this;
      }
      Companion_5.prototype.fromClosedRange_vhxzyy_k$ = function(rangeStart, rangeEnd, step) {
        return new IntProgression(rangeStart, rangeEnd, step);
      };
      Companion_5.$metadata$ = objectMeta("Companion");
      var Companion_instance_5;
      function Companion_getInstance_5() {
        if (Companion_instance_5 == null)
          new Companion_5();
        return Companion_instance_5;
      }
      function IntProgression(start2, endInclusive, step) {
        Companion_getInstance_5();
        if (step === 0)
          throw IllegalArgumentException_init_$Create$_0("Step must be non-zero.");
        if (step === IntCompanionObject_getInstance().MIN_VALUE_1)
          throw IllegalArgumentException_init_$Create$_0("Step must be greater than Int.MIN_VALUE to avoid overflow on negation.");
        this.first_1 = start2;
        this.last_1 = getProgressionLastElement(start2, endInclusive, step);
        this.step_1 = step;
      }
      IntProgression.prototype.get_first_irdx8n_k$ = function() {
        return this.first_1;
      };
      IntProgression.prototype.get_last_wopotb_k$ = function() {
        return this.last_1;
      };
      IntProgression.prototype.get_step_woujh1_k$ = function() {
        return this.step_1;
      };
      IntProgression.prototype.iterator_jk1svi_k$ = function() {
        return new IntProgressionIterator(this.first_1, this.last_1, this.step_1);
      };
      IntProgression.prototype.isEmpty_y1axqb_k$ = function() {
        return this.step_1 > 0 ? this.first_1 > this.last_1 : this.first_1 < this.last_1;
      };
      IntProgression.prototype.equals = function(other) {
        var tmp;
        if (other instanceof IntProgression) {
          tmp = (this.isEmpty_y1axqb_k$() ? other.isEmpty_y1axqb_k$() : false) ? true : (this.first_1 === other.first_1 ? this.last_1 === other.last_1 : false) ? this.step_1 === other.step_1 : false;
        } else {
          tmp = false;
        }
        return tmp;
      };
      IntProgression.prototype.hashCode = function() {
        return this.isEmpty_y1axqb_k$() ? -1 : imul(31, imul(31, this.first_1) + this.last_1 | 0) + this.step_1 | 0;
      };
      IntProgression.prototype.toString = function() {
        return this.step_1 > 0 ? "" + this.first_1 + ".." + this.last_1 + " step " + this.step_1 : "" + this.first_1 + " downTo " + this.last_1 + " step " + (-this.step_1 | 0);
      };
      IntProgression.$metadata$ = classMeta("IntProgression", [Iterable]);
      function Companion_6() {
        Companion_instance_6 = this;
      }
      Companion_6.prototype.fromClosedRange_kxji4u_k$ = function(rangeStart, rangeEnd, step) {
        return new CharProgression(rangeStart, rangeEnd, step);
      };
      Companion_6.$metadata$ = objectMeta("Companion");
      var Companion_instance_6;
      function Companion_getInstance_6() {
        if (Companion_instance_6 == null)
          new Companion_6();
        return Companion_instance_6;
      }
      function CharProgression(start2, endInclusive, step) {
        Companion_getInstance_6();
        if (step === 0)
          throw IllegalArgumentException_init_$Create$_0("Step must be non-zero.");
        if (step === IntCompanionObject_getInstance().MIN_VALUE_1)
          throw IllegalArgumentException_init_$Create$_0("Step must be greater than Int.MIN_VALUE to avoid overflow on negation.");
        this.first_1 = start2;
        var tmp = this;
        var tmp$ret$0;
        tmp$ret$0 = Char__toInt_impl_vasixd(start2);
        var tmp_0 = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = Char__toInt_impl_vasixd(endInclusive);
        tmp.last_1 = numberToChar(getProgressionLastElement(tmp_0, tmp$ret$1, step));
        this.step_1 = step;
      }
      CharProgression.prototype.get_first_en5qmg_k$ = function() {
        return this.first_1;
      };
      CharProgression.prototype.get_last_rp1s9s_k$ = function() {
        return this.last_1;
      };
      CharProgression.prototype.get_step_woujh1_k$ = function() {
        return this.step_1;
      };
      CharProgression.prototype.iterator_jk1svi_k$ = function() {
        return new CharProgressionIterator(this.first_1, this.last_1, this.step_1);
      };
      CharProgression.prototype.isEmpty_y1axqb_k$ = function() {
        return this.step_1 > 0 ? Char__compareTo_impl_ypi4mb(this.first_1, this.last_1) > 0 : Char__compareTo_impl_ypi4mb(this.first_1, this.last_1) < 0;
      };
      CharProgression.prototype.equals = function(other) {
        var tmp;
        if (other instanceof CharProgression) {
          tmp = (this.isEmpty_y1axqb_k$() ? other.isEmpty_y1axqb_k$() : false) ? true : (equals(new Char_0(this.first_1), new Char_0(other.first_1)) ? equals(new Char_0(this.last_1), new Char_0(other.last_1)) : false) ? this.step_1 === other.step_1 : false;
        } else {
          tmp = false;
        }
        return tmp;
      };
      CharProgression.prototype.hashCode = function() {
        var tmp;
        if (this.isEmpty_y1axqb_k$()) {
          tmp = -1;
        } else {
          var tmp$ret$0;
          var tmp0__get_code__88qj9g = this.first_1;
          tmp$ret$0 = Char__toInt_impl_vasixd(tmp0__get_code__88qj9g);
          var tmp_0 = imul(31, tmp$ret$0);
          var tmp$ret$1;
          var tmp1__get_code__adl84j = this.last_1;
          tmp$ret$1 = Char__toInt_impl_vasixd(tmp1__get_code__adl84j);
          tmp = imul(31, tmp_0 + tmp$ret$1 | 0) + this.step_1 | 0;
        }
        return tmp;
      };
      CharProgression.prototype.toString = function() {
        return this.step_1 > 0 ? "" + new Char_0(this.first_1) + ".." + new Char_0(this.last_1) + " step " + this.step_1 : "" + new Char_0(this.first_1) + " downTo " + new Char_0(this.last_1) + " step " + (-this.step_1 | 0);
      };
      CharProgression.$metadata$ = classMeta("CharProgression", [Iterable]);
      function Companion_7() {
        Companion_instance_7 = this;
      }
      Companion_7.prototype.fromClosedRange_5n0x23_k$ = function(rangeStart, rangeEnd, step) {
        return new LongProgression(rangeStart, rangeEnd, step);
      };
      Companion_7.$metadata$ = objectMeta("Companion");
      var Companion_instance_7;
      function Companion_getInstance_7() {
        if (Companion_instance_7 == null)
          new Companion_7();
        return Companion_instance_7;
      }
      function LongProgression(start2, endInclusive, step) {
        Companion_getInstance_7();
        if (step.equals(new Long(0, 0)))
          throw IllegalArgumentException_init_$Create$_0("Step must be non-zero.");
        Companion_getInstance_20();
        if (step.equals(new Long(0, -2147483648)))
          throw IllegalArgumentException_init_$Create$_0("Step must be greater than Long.MIN_VALUE to avoid overflow on negation.");
        this.first_1 = start2;
        this.last_1 = getProgressionLastElement_0(start2, endInclusive, step);
        this.step_1 = step;
      }
      LongProgression.prototype.get_first_irdx8n_k$ = function() {
        return this.first_1;
      };
      LongProgression.prototype.get_last_wopotb_k$ = function() {
        return this.last_1;
      };
      LongProgression.prototype.get_step_woujh1_k$ = function() {
        return this.step_1;
      };
      LongProgression.prototype.iterator_jk1svi_k$ = function() {
        return new LongProgressionIterator(this.first_1, this.last_1, this.step_1);
      };
      LongProgression.prototype.isEmpty_y1axqb_k$ = function() {
        return this.step_1.compareTo_n4fqi2_k$(new Long(0, 0)) > 0 ? this.first_1.compareTo_n4fqi2_k$(this.last_1) > 0 : this.first_1.compareTo_n4fqi2_k$(this.last_1) < 0;
      };
      LongProgression.prototype.equals = function(other) {
        var tmp;
        if (other instanceof LongProgression) {
          tmp = (this.isEmpty_y1axqb_k$() ? other.isEmpty_y1axqb_k$() : false) ? true : (this.first_1.equals(other.first_1) ? this.last_1.equals(other.last_1) : false) ? this.step_1.equals(other.step_1) : false;
        } else {
          tmp = false;
        }
        return tmp;
      };
      LongProgression.prototype.hashCode = function() {
        return this.isEmpty_y1axqb_k$() ? -1 : numberToLong(31).times_2zfqpc_k$(numberToLong(31).times_2zfqpc_k$(this.first_1.xor_jjua9n_k$(this.first_1.ushr_rr8rvr_k$(32))).plus_u6jwas_k$(this.last_1.xor_jjua9n_k$(this.last_1.ushr_rr8rvr_k$(32)))).plus_u6jwas_k$(this.step_1.xor_jjua9n_k$(this.step_1.ushr_rr8rvr_k$(32))).toInt_1tsl84_k$();
      };
      LongProgression.prototype.toString = function() {
        return this.step_1.compareTo_n4fqi2_k$(new Long(0, 0)) > 0 ? toString_1(this.first_1) + ".." + toString_1(this.last_1) + " step " + toString_1(this.step_1) : toString_1(this.first_1) + " downTo " + toString_1(this.last_1) + " step " + toString_1(this.step_1.unaryMinus_6uz0qp_k$());
      };
      LongProgression.$metadata$ = classMeta("LongProgression", [Iterable]);
      function ClosedRange() {
      }
      ClosedRange.$metadata$ = interfaceMeta("ClosedRange");
      function OpenEndRange() {
      }
      OpenEndRange.$metadata$ = interfaceMeta("OpenEndRange");
      function KClassifier() {
      }
      KClassifier.$metadata$ = interfaceMeta("KClassifier");
      function KTypeParameter() {
      }
      KTypeParameter.$metadata$ = interfaceMeta("KTypeParameter", [KClassifier]);
      function Companion_8() {
        Companion_instance_8 = this;
        this.star_1 = new KTypeProjection(null, null);
      }
      Companion_8.prototype.get_star_woujdn_k$ = function() {
        return this.star_1;
      };
      Companion_8.prototype.get_STAR_wo9fa3_k$ = function() {
        return this.star_1;
      };
      Companion_8.prototype.invariant_d1std2_k$ = function(type) {
        return new KTypeProjection(KVariance_INVARIANT_getInstance(), type);
      };
      Companion_8.prototype.contravariant_lnygde_k$ = function(type) {
        return new KTypeProjection(KVariance_IN_getInstance(), type);
      };
      Companion_8.prototype.covariant_ne14kt_k$ = function(type) {
        return new KTypeProjection(KVariance_OUT_getInstance(), type);
      };
      Companion_8.$metadata$ = objectMeta("Companion");
      var Companion_instance_8;
      function Companion_getInstance_8() {
        if (Companion_instance_8 == null)
          new Companion_8();
        return Companion_instance_8;
      }
      function KTypeProjection(variance, type) {
        Companion_getInstance_8();
        this.variance_1 = variance;
        this.type_1 = type;
        var tmp0_require = this.variance_1 == null === (this.type_1 == null);
        if (!tmp0_require) {
          var tmp$ret$0;
          tmp$ret$0 = this.variance_1 == null ? "Star projection must have no type specified." : "The projection variance " + this.variance_1 + " requires type to be specified.";
          var message = tmp$ret$0;
          throw IllegalArgumentException_init_$Create$_0(toString_1(message));
        }
      }
      KTypeProjection.prototype.get_variance_ik7ku2_k$ = function() {
        return this.variance_1;
      };
      KTypeProjection.prototype.get_type_wovaf7_k$ = function() {
        return this.type_1;
      };
      KTypeProjection.prototype.toString = function() {
        var tmp0_subject = this.variance_1;
        var tmp0 = tmp0_subject == null ? -1 : tmp0_subject.ordinal_1;
        var tmp;
        switch (tmp0) {
          case -1:
            tmp = "*";
            break;
          case 0:
            tmp = toString_0(this.type_1);
            break;
          case 1:
            tmp = "in " + this.type_1;
            break;
          case 2:
            tmp = "out " + this.type_1;
            break;
          default:
            noWhenBranchMatchedException();
            break;
        }
        return tmp;
      };
      KTypeProjection.prototype.component1_7eebsc_k$ = function() {
        return this.variance_1;
      };
      KTypeProjection.prototype.component2_7eebsb_k$ = function() {
        return this.type_1;
      };
      KTypeProjection.prototype.copy_luz5xs_k$ = function(variance, type) {
        return new KTypeProjection(variance, type);
      };
      KTypeProjection.prototype.copy$default_yujqmj_k$ = function(variance, type, $mask0, $handler) {
        if (!(($mask0 & 1) === 0))
          variance = this.variance_1;
        if (!(($mask0 & 2) === 0))
          type = this.type_1;
        return this.copy_luz5xs_k$(variance, type);
      };
      KTypeProjection.prototype.hashCode = function() {
        var result = this.variance_1 == null ? 0 : this.variance_1.hashCode();
        result = imul(result, 31) + (this.type_1 == null ? 0 : hashCode(this.type_1)) | 0;
        return result;
      };
      KTypeProjection.prototype.equals = function(other) {
        if (this === other)
          return true;
        if (!(other instanceof KTypeProjection))
          return false;
        var tmp0_other_with_cast = other instanceof KTypeProjection ? other : THROW_CCE();
        if (!equals(this.variance_1, tmp0_other_with_cast.variance_1))
          return false;
        if (!equals(this.type_1, tmp0_other_with_cast.type_1))
          return false;
        return true;
      };
      KTypeProjection.$metadata$ = classMeta("KTypeProjection");
      var KVariance_INVARIANT_instance;
      var KVariance_IN_instance;
      var KVariance_OUT_instance;
      function values_2() {
        return [KVariance_INVARIANT_getInstance(), KVariance_IN_getInstance(), KVariance_OUT_getInstance()];
      }
      function valueOf_2(value) {
        switch (value) {
          case "INVARIANT":
            return KVariance_INVARIANT_getInstance();
          case "IN":
            return KVariance_IN_getInstance();
          case "OUT":
            return KVariance_OUT_getInstance();
          default:
            KVariance_initEntries();
            THROW_ISE();
            break;
        }
      }
      var KVariance_entriesInitialized;
      function KVariance_initEntries() {
        if (KVariance_entriesInitialized)
          return Unit_getInstance();
        KVariance_entriesInitialized = true;
        KVariance_INVARIANT_instance = new KVariance("INVARIANT", 0);
        KVariance_IN_instance = new KVariance("IN", 1);
        KVariance_OUT_instance = new KVariance("OUT", 2);
      }
      function KVariance(name, ordinal) {
        Enum.call(this, name, ordinal);
      }
      KVariance.$metadata$ = classMeta("KVariance", void 0, void 0, void 0, void 0, Enum.prototype);
      function KVariance_INVARIANT_getInstance() {
        KVariance_initEntries();
        return KVariance_INVARIANT_instance;
      }
      function KVariance_IN_getInstance() {
        KVariance_initEntries();
        return KVariance_IN_instance;
      }
      function KVariance_OUT_getInstance() {
        KVariance_initEntries();
        return KVariance_OUT_instance;
      }
      function appendElement(_this__u8e3s4, element, transform2) {
        if (!(transform2 == null)) {
          _this__u8e3s4.append_oz4qxs_k$(transform2(element));
        } else {
          if (element == null ? true : isCharSequence(element)) {
            _this__u8e3s4.append_oz4qxs_k$(element);
          } else {
            if (element instanceof Char_0) {
              _this__u8e3s4.append_t8oh9e_k$(element.value_1);
            } else {
              _this__u8e3s4.append_oz4qxs_k$(toString_0(element));
            }
          }
        }
      }
      function isEmpty_1(_this__u8e3s4) {
        return charSequenceLength(_this__u8e3s4) === 0;
      }
      function get_lastIndex_7(_this__u8e3s4) {
        return charSequenceLength(_this__u8e3s4) - 1 | 0;
      }
      function get_UNDEFINED_RESULT() {
        init_properties_DeepRecursive_kt_b2anle();
        return UNDEFINED_RESULT;
      }
      var UNDEFINED_RESULT;
      var properties_initialized_DeepRecursive_kt_5z0al2;
      function init_properties_DeepRecursive_kt_b2anle() {
        if (properties_initialized_DeepRecursive_kt_5z0al2) {
        } else {
          properties_initialized_DeepRecursive_kt_5z0al2 = true;
          var tmp$ret$0;
          var tmp0_success = Companion_getInstance_9();
          var tmp1_success = get_COROUTINE_SUSPENDED();
          tmp$ret$0 = _Result___init__impl__xyqfz8(tmp1_success);
          UNDEFINED_RESULT = tmp$ret$0;
        }
      }
      function error51(message) {
        throw IllegalStateException_init_$Create$_0(toString_1(message));
      }
      function check2(value) {
        if (!value) {
          var tmp$ret$0;
          tmp$ret$0 = "Check failed.";
          var message = tmp$ret$0;
          throw IllegalStateException_init_$Create$_0(toString_1(message));
        }
      }
      function check_0(value, lazyMessage) {
        if (!value) {
          var message = lazyMessage();
          throw IllegalStateException_init_$Create$_0(toString_1(message));
        }
      }
      function require_0(value, lazyMessage) {
        if (!value) {
          var message = lazyMessage();
          throw IllegalArgumentException_init_$Create$_0(toString_1(message));
        }
      }
      function _Result___init__impl__xyqfz8(value) {
        return value;
      }
      function _Result___get_value__impl__bjfvqg($this) {
        return $this;
      }
      function _Result___get_isSuccess__impl__sndoy8($this) {
        var tmp = _Result___get_value__impl__bjfvqg($this);
        return !(tmp instanceof Failure);
      }
      function _Result___get_isFailure__impl__jpiriv($this) {
        var tmp = _Result___get_value__impl__bjfvqg($this);
        return tmp instanceof Failure;
      }
      function Result__getOrNull_impl_x6tyqe($this) {
        var tmp;
        if (_Result___get_isFailure__impl__jpiriv($this)) {
          tmp = null;
        } else {
          var tmp_0 = _Result___get_value__impl__bjfvqg($this);
          tmp = (tmp_0 == null ? true : isObject3(tmp_0)) ? tmp_0 : THROW_CCE();
        }
        return tmp;
      }
      function Result__exceptionOrNull_impl_p6xea9($this) {
        var tmp0_subject = _Result___get_value__impl__bjfvqg($this);
        var tmp;
        if (tmp0_subject instanceof Failure) {
          tmp = _Result___get_value__impl__bjfvqg($this).exception_1;
        } else {
          tmp = null;
        }
        return tmp;
      }
      function Result__toString_impl_yu5r8k($this) {
        var tmp0_subject = _Result___get_value__impl__bjfvqg($this);
        var tmp;
        if (tmp0_subject instanceof Failure) {
          tmp = toString_1(_Result___get_value__impl__bjfvqg($this));
        } else {
          tmp = "Success(" + toString_0(_Result___get_value__impl__bjfvqg($this)) + ")";
        }
        return tmp;
      }
      function Companion_9() {
        Companion_instance_9 = this;
      }
      Companion_9.prototype.success_5n1c7s_k$ = function(value) {
        return _Result___init__impl__xyqfz8(value);
      };
      Companion_9.prototype.failure_tk7s8q_k$ = function(exception) {
        return _Result___init__impl__xyqfz8(createFailure(exception));
      };
      Companion_9.$metadata$ = objectMeta("Companion");
      var Companion_instance_9;
      function Companion_getInstance_9() {
        if (Companion_instance_9 == null)
          new Companion_9();
        return Companion_instance_9;
      }
      function Failure(exception) {
        this.exception_1 = exception;
      }
      Failure.prototype.get_exception_x0n6w6_k$ = function() {
        return this.exception_1;
      };
      Failure.prototype.equals = function(other) {
        var tmp;
        if (other instanceof Failure) {
          tmp = equals(this.exception_1, other.exception_1);
        } else {
          tmp = false;
        }
        return tmp;
      };
      Failure.prototype.hashCode = function() {
        return hashCode(this.exception_1);
      };
      Failure.prototype.toString = function() {
        return "Failure(" + this.exception_1 + ")";
      };
      Failure.$metadata$ = classMeta("Failure", [Serializable]);
      function Result__hashCode_impl_d2zufp($this) {
        return $this == null ? 0 : hashCode($this);
      }
      function Result__equals_impl_bxgmep($this, other) {
        if (!(other instanceof Result))
          return false;
        var tmp0_other_with_cast = other instanceof Result ? other.value_1 : THROW_CCE();
        if (!equals($this, tmp0_other_with_cast))
          return false;
        return true;
      }
      function Result(value) {
        Companion_getInstance_9();
        this.value_1 = value;
      }
      Result.prototype.toString = function() {
        return Result__toString_impl_yu5r8k(this.value_1);
      };
      Result.prototype.hashCode = function() {
        return Result__hashCode_impl_d2zufp(this.value_1);
      };
      Result.prototype.equals = function(other) {
        return Result__equals_impl_bxgmep(this.value_1, other);
      };
      Result.$metadata$ = classMeta("Result", [Serializable]);
      function createFailure(exception) {
        return new Failure(exception);
      }
      function getOrThrow(_this__u8e3s4) {
        throwOnFailure(_this__u8e3s4);
        var tmp = _Result___get_value__impl__bjfvqg(_this__u8e3s4);
        return (tmp == null ? true : isObject3(tmp)) ? tmp : THROW_CCE();
      }
      function throwOnFailure(_this__u8e3s4) {
        var tmp = _Result___get_value__impl__bjfvqg(_this__u8e3s4);
        if (tmp instanceof Failure)
          throw _Result___get_value__impl__bjfvqg(_this__u8e3s4).exception_1;
      }
      function run(block) {
        return block();
      }
      function TODO() {
        throw NotImplementedError_init_$Create$(null, 1, null);
      }
      function NotImplementedError_init_$Init$(message, $mask0, $marker, $this) {
        if (!(($mask0 & 1) === 0))
          message = "An operation is not implemented.";
        NotImplementedError.call($this, message);
        return $this;
      }
      function NotImplementedError_init_$Create$(message, $mask0, $marker) {
        var tmp = NotImplementedError_init_$Init$(message, $mask0, $marker, Object.create(NotImplementedError.prototype));
        captureStack(tmp, NotImplementedError_init_$Create$);
        return tmp;
      }
      function NotImplementedError(message) {
        Error_init_$Init$_0(message, this);
        captureStack(this, NotImplementedError);
      }
      NotImplementedError.$metadata$ = classMeta("NotImplementedError", void 0, void 0, void 0, void 0, Error_0.prototype);
      function let_0(_this__u8e3s4, block) {
        return block(_this__u8e3s4);
      }
      function apply(_this__u8e3s4, block) {
        block(_this__u8e3s4);
        return _this__u8e3s4;
      }
      function repeat(times, action) {
        var inductionVariable = 0;
        if (inductionVariable < times)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            action(index);
          } while (inductionVariable < times);
      }
      function with_0(receiver, block) {
        return block(receiver);
      }
      function run_0(_this__u8e3s4, block) {
        return block(_this__u8e3s4);
      }
      function also(_this__u8e3s4, block) {
        block(_this__u8e3s4);
        return _this__u8e3s4;
      }
      function _UByte___init__impl__g9hnc4(data) {
        return data;
      }
      function _UByte___get_data__impl__jof9qr($this) {
        return $this;
      }
      function Companion_10() {
        Companion_instance_10 = this;
        this.MIN_VALUE_1 = _UByte___init__impl__g9hnc4(0);
        this.MAX_VALUE_1 = _UByte___init__impl__g9hnc4(-1);
        this.SIZE_BYTES_1 = 1;
        this.SIZE_BITS_1 = 8;
      }
      Companion_10.prototype.get_MIN_VALUE_p0dmjb_k$ = function() {
        return this.MIN_VALUE_1;
      };
      Companion_10.prototype.get_MAX_VALUE_4mpz45_k$ = function() {
        return this.MAX_VALUE_1;
      };
      Companion_10.prototype.get_SIZE_BYTES_qphg4q_k$ = function() {
        return this.SIZE_BYTES_1;
      };
      Companion_10.prototype.get_SIZE_BITS_7qhjj9_k$ = function() {
        return this.SIZE_BITS_1;
      };
      Companion_10.$metadata$ = objectMeta("Companion");
      var Companion_instance_10;
      function Companion_getInstance_10() {
        if (Companion_instance_10 == null)
          new Companion_10();
        return Companion_instance_10;
      }
      function UByte__compareTo_impl_5w5192($this, other) {
        var tmp$ret$0;
        tmp$ret$0 = _UByte___get_data__impl__jof9qr($this) & 255;
        var tmp = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UByte___get_data__impl__jof9qr(other) & 255;
        return compareTo_0(tmp, tmp$ret$1);
      }
      function UByte__compareTo_impl_5w5192_0($this, other) {
        var tmp = $this.data_1;
        return UByte__compareTo_impl_5w5192(tmp, other instanceof UByte ? other.data_1 : THROW_CCE());
      }
      function UByte__compareTo_impl_5w5192_1($this, other) {
        var tmp$ret$0;
        tmp$ret$0 = _UByte___get_data__impl__jof9qr($this) & 255;
        var tmp = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UShort___get_data__impl__g0245(other) & 65535;
        return compareTo_0(tmp, tmp$ret$1);
      }
      function UByte__compareTo_impl_5w5192_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_compareTo = tmp$ret$0;
        tmp$ret$1 = uintCompare(_UInt___get_data__impl__f0vqqw(tmp0_compareTo), _UInt___get_data__impl__f0vqqw(other));
        return tmp$ret$1;
      }
      function UByte__compareTo_impl_5w5192_3($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr($this)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_compareTo = tmp$ret$0;
        tmp$ret$1 = ulongCompare(_ULong___get_data__impl__fggpzb(tmp0_compareTo), _ULong___get_data__impl__fggpzb(other));
        return tmp$ret$1;
      }
      function UByte__plus_impl_y9dsom($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_plus = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_plus = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_plus) + _UInt___get_data__impl__f0vqqw(tmp1_plus) | 0);
        return tmp$ret$2;
      }
      function UByte__plus_impl_y9dsom_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_plus = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_plus = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_plus) + _UInt___get_data__impl__f0vqqw(tmp1_plus) | 0);
        return tmp$ret$2;
      }
      function UByte__plus_impl_y9dsom_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_plus = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_plus) + _UInt___get_data__impl__f0vqqw(other) | 0);
        return tmp$ret$1;
      }
      function UByte__plus_impl_y9dsom_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr($this)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_plus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_plus).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(other)));
        return tmp$ret$1;
      }
      function UByte__minus_impl_qw5fay($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_minus = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_minus = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_minus) - _UInt___get_data__impl__f0vqqw(tmp1_minus) | 0);
        return tmp$ret$2;
      }
      function UByte__minus_impl_qw5fay_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_minus = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_minus = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_minus) - _UInt___get_data__impl__f0vqqw(tmp1_minus) | 0);
        return tmp$ret$2;
      }
      function UByte__minus_impl_qw5fay_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_minus = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_minus) - _UInt___get_data__impl__f0vqqw(other) | 0);
        return tmp$ret$1;
      }
      function UByte__minus_impl_qw5fay_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr($this)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_minus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_minus).minus_llf5ei_k$(_ULong___get_data__impl__fggpzb(other)));
        return tmp$ret$1;
      }
      function UByte__times_impl_olmv1g($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_times = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_times = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(imul(_UInt___get_data__impl__f0vqqw(tmp0_times), _UInt___get_data__impl__f0vqqw(tmp1_times)));
        return tmp$ret$2;
      }
      function UByte__times_impl_olmv1g_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_times = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_times = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(imul(_UInt___get_data__impl__f0vqqw(tmp0_times), _UInt___get_data__impl__f0vqqw(tmp1_times)));
        return tmp$ret$2;
      }
      function UByte__times_impl_olmv1g_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_times = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(imul(_UInt___get_data__impl__f0vqqw(tmp0_times), _UInt___get_data__impl__f0vqqw(other)));
        return tmp$ret$1;
      }
      function UByte__times_impl_olmv1g_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr($this)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_times = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_times).times_2zfqpc_k$(_ULong___get_data__impl__fggpzb(other)));
        return tmp$ret$1;
      }
      function UByte__div_impl_fvt4lj($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_div = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_div = tmp$ret$1;
        tmp$ret$2 = uintDivide(tmp0_div, tmp1_div);
        return tmp$ret$2;
      }
      function UByte__div_impl_fvt4lj_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_div = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_div = tmp$ret$1;
        tmp$ret$2 = uintDivide(tmp0_div, tmp1_div);
        return tmp$ret$2;
      }
      function UByte__div_impl_fvt4lj_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_div = tmp$ret$0;
        tmp$ret$1 = uintDivide(tmp0_div, other);
        return tmp$ret$1;
      }
      function UByte__div_impl_fvt4lj_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr($this)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_div = tmp$ret$0;
        tmp$ret$1 = ulongDivide(tmp0_div, other);
        return tmp$ret$1;
      }
      function UByte__rem_impl_uhmi28($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_rem = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_rem = tmp$ret$1;
        tmp$ret$2 = uintRemainder(tmp0_rem, tmp1_rem);
        return tmp$ret$2;
      }
      function UByte__rem_impl_uhmi28_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_rem = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_rem = tmp$ret$1;
        tmp$ret$2 = uintRemainder(tmp0_rem, tmp1_rem);
        return tmp$ret$2;
      }
      function UByte__rem_impl_uhmi28_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_rem = tmp$ret$0;
        tmp$ret$1 = uintRemainder(tmp0_rem, other);
        return tmp$ret$1;
      }
      function UByte__rem_impl_uhmi28_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr($this)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_rem = tmp$ret$0;
        tmp$ret$1 = ulongRemainder(tmp0_rem, other);
        return tmp$ret$1;
      }
      function UByte__floorDiv_impl_twf9fv($this, other) {
        var tmp$ret$3;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_floorDiv = tmp$ret$1;
        var tmp$ret$2;
        tmp$ret$2 = uintDivide(tmp0_floorDiv, tmp1_floorDiv);
        tmp$ret$3 = tmp$ret$2;
        return tmp$ret$3;
      }
      function UByte__floorDiv_impl_twf9fv_0($this, other) {
        var tmp$ret$3;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_floorDiv = tmp$ret$1;
        var tmp$ret$2;
        tmp$ret$2 = uintDivide(tmp0_floorDiv, tmp1_floorDiv);
        tmp$ret$3 = tmp$ret$2;
        return tmp$ret$3;
      }
      function UByte__floorDiv_impl_twf9fv_1($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = uintDivide(tmp0_floorDiv, other);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UByte__floorDiv_impl_twf9fv_2($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr($this)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongDivide(tmp0_floorDiv, other);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UByte__mod_impl_w36moo($this, other) {
        var tmp$ret$5;
        var tmp$ret$3;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_mod = tmp$ret$1;
        var tmp$ret$2;
        tmp$ret$2 = uintRemainder(tmp0_mod, tmp1_mod);
        tmp$ret$3 = tmp$ret$2;
        var tmp3_toUByte = tmp$ret$3;
        var tmp$ret$4;
        var tmp2_toUByte = _UInt___get_data__impl__f0vqqw(tmp3_toUByte);
        tmp$ret$4 = _UByte___init__impl__g9hnc4(toByte(tmp2_toUByte));
        tmp$ret$5 = tmp$ret$4;
        return tmp$ret$5;
      }
      function UByte__mod_impl_w36moo_0($this, other) {
        var tmp$ret$5;
        var tmp$ret$3;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_mod = tmp$ret$1;
        var tmp$ret$2;
        tmp$ret$2 = uintRemainder(tmp0_mod, tmp1_mod);
        tmp$ret$3 = tmp$ret$2;
        var tmp3_toUShort = tmp$ret$3;
        var tmp$ret$4;
        var tmp2_toUShort = _UInt___get_data__impl__f0vqqw(tmp3_toUShort);
        tmp$ret$4 = _UShort___init__impl__jigrne(toShort(tmp2_toUShort));
        tmp$ret$5 = tmp$ret$4;
        return tmp$ret$5;
      }
      function UByte__mod_impl_w36moo_1($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = uintRemainder(tmp0_mod, other);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UByte__mod_impl_w36moo_2($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr($this)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongRemainder(tmp0_mod, other);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UByte__inc_impl_kgwblg($this) {
        return _UByte___init__impl__g9hnc4(numberToByte(_UByte___get_data__impl__jof9qr($this) + 1));
      }
      function UByte__dec_impl_ck5108($this) {
        return _UByte___init__impl__g9hnc4(numberToByte(_UByte___get_data__impl__jof9qr($this) - 1));
      }
      function UByte__rangeTo_impl_pp550u($this, other) {
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
        var tmp = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        return new UIntRange(tmp, tmp$ret$1);
      }
      function UByte__and_impl_xjlq7n($this, other) {
        var tmp$ret$0;
        var tmp0_and = _UByte___get_data__impl__jof9qr($this);
        var tmp1_and = _UByte___get_data__impl__jof9qr(other);
        tmp$ret$0 = toByte(tmp0_and & tmp1_and);
        return _UByte___init__impl__g9hnc4(tmp$ret$0);
      }
      function UByte__or_impl_hh1w25($this, other) {
        var tmp$ret$0;
        var tmp0_or = _UByte___get_data__impl__jof9qr($this);
        var tmp1_or = _UByte___get_data__impl__jof9qr(other);
        tmp$ret$0 = toByte(tmp0_or | tmp1_or);
        return _UByte___init__impl__g9hnc4(tmp$ret$0);
      }
      function UByte__xor_impl_7gv2lr($this, other) {
        var tmp$ret$0;
        var tmp0_xor = _UByte___get_data__impl__jof9qr($this);
        var tmp1_xor = _UByte___get_data__impl__jof9qr(other);
        tmp$ret$0 = toByte(tmp0_xor ^ tmp1_xor);
        return _UByte___init__impl__g9hnc4(tmp$ret$0);
      }
      function UByte__inv_impl_bh1i3r($this) {
        var tmp$ret$0;
        var tmp0_inv = _UByte___get_data__impl__jof9qr($this);
        tmp$ret$0 = toByte(~tmp0_inv);
        return _UByte___init__impl__g9hnc4(tmp$ret$0);
      }
      function UByte__toByte_impl_h2o6a5($this) {
        return _UByte___get_data__impl__jof9qr($this);
      }
      function UByte__toShort_impl_3us8xj($this) {
        var tmp$ret$0;
        var tmp0_and = _UByte___get_data__impl__jof9qr($this);
        tmp$ret$0 = toShort(tmp0_and & 255);
        return tmp$ret$0;
      }
      function UByte__toInt_impl_5nso52($this) {
        return _UByte___get_data__impl__jof9qr($this) & 255;
      }
      function UByte__toLong_impl_hwyqzr($this) {
        return toLong(_UByte___get_data__impl__jof9qr($this)).and_jhajnj_k$(new Long(255, 0));
      }
      function UByte__toUByte_impl_fekj48($this) {
        return $this;
      }
      function UByte__toUShort_impl_ff6uy6($this) {
        var tmp$ret$0;
        var tmp0_and = _UByte___get_data__impl__jof9qr($this);
        tmp$ret$0 = toShort(tmp0_and & 255);
        return _UShort___init__impl__jigrne(tmp$ret$0);
      }
      function UByte__toUInt_impl_qgytr9($this) {
        return _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr($this) & 255);
      }
      function UByte__toULong_impl_jl2e5o($this) {
        return _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr($this)).and_jhajnj_k$(new Long(255, 0)));
      }
      function UByte__toFloat_impl_ogkoa1($this) {
        var tmp$ret$0;
        tmp$ret$0 = _UByte___get_data__impl__jof9qr($this) & 255;
        return tmp$ret$0;
      }
      function UByte__toDouble_impl_2n4zfg($this) {
        var tmp$ret$0;
        tmp$ret$0 = _UByte___get_data__impl__jof9qr($this) & 255;
        return tmp$ret$0;
      }
      function UByte__toString_impl_v72jg($this) {
        var tmp$ret$0;
        tmp$ret$0 = _UByte___get_data__impl__jof9qr($this) & 255;
        return tmp$ret$0.toString();
      }
      function UByte__hashCode_impl_mmczcb($this) {
        return $this;
      }
      function UByte__equals_impl_nvqtsf($this, other) {
        if (!(other instanceof UByte))
          return false;
        var tmp0_other_with_cast = other instanceof UByte ? other.data_1 : THROW_CCE();
        if (!($this === tmp0_other_with_cast))
          return false;
        return true;
      }
      function UByte(data) {
        Companion_getInstance_10();
        this.data_1 = data;
      }
      UByte.prototype.compareTo_6mkx9r_k$ = function(other) {
        return UByte__compareTo_impl_5w5192(this.data_1, other);
      };
      UByte.prototype.compareTo_6thzaj_k$ = function(other) {
        return UByte__compareTo_impl_5w5192_0(this, other);
      };
      UByte.prototype.toString = function() {
        return UByte__toString_impl_v72jg(this.data_1);
      };
      UByte.prototype.hashCode = function() {
        return UByte__hashCode_impl_mmczcb(this.data_1);
      };
      UByte.prototype.equals = function(other) {
        return UByte__equals_impl_nvqtsf(this.data_1, other);
      };
      UByte.$metadata$ = classMeta("UByte", [Comparable]);
      function toUByte(_this__u8e3s4) {
        return _UByte___init__impl__g9hnc4(toByte(_this__u8e3s4));
      }
      function toUByte_0(_this__u8e3s4) {
        return _UByte___init__impl__g9hnc4(toByte(_this__u8e3s4));
      }
      function toUByte_1(_this__u8e3s4) {
        return _UByte___init__impl__g9hnc4(_this__u8e3s4.toByte_edm0nx_k$());
      }
      function toUByte_2(_this__u8e3s4) {
        return _UByte___init__impl__g9hnc4(_this__u8e3s4);
      }
      function _get_array__jslnqg($this) {
        return $this.array_1;
      }
      function _set_index__fyfqnn($this, _set____db54di) {
        $this.index_1 = _set____db54di;
      }
      function _get_index__g2optt($this) {
        return $this.index_1;
      }
      function _UByteArray___init__impl__ip4y9n(storage) {
        return storage;
      }
      function _UByteArray___get_storage__impl__d4kctt($this) {
        return $this;
      }
      function _UByteArray___init__impl__ip4y9n_0(size2) {
        var tmp = _UByteArray___init__impl__ip4y9n(new Int8Array(size2));
        return tmp;
      }
      function UByteArray__get_impl_t5f3hv($this, index) {
        var tmp$ret$0;
        var tmp0_toUByte = _UByteArray___get_storage__impl__d4kctt($this)[index];
        tmp$ret$0 = _UByte___init__impl__g9hnc4(tmp0_toUByte);
        return tmp$ret$0;
      }
      function UByteArray__set_impl_jvcicn($this, index, value) {
        var tmp = _UByteArray___get_storage__impl__d4kctt($this);
        var tmp$ret$0;
        tmp$ret$0 = _UByte___get_data__impl__jof9qr(value);
        tmp[index] = tmp$ret$0;
      }
      function _UByteArray___get_size__impl__h6pkdv($this) {
        return _UByteArray___get_storage__impl__d4kctt($this).length;
      }
      function UByteArray__iterator_impl_509y1p($this) {
        return new Iterator(_UByteArray___get_storage__impl__d4kctt($this));
      }
      function Iterator(array3) {
        this.array_1 = array3;
        this.index_1 = 0;
      }
      Iterator.prototype.hasNext_bitz1p_k$ = function() {
        return this.index_1 < this.array_1.length;
      };
      Iterator.prototype.next_mzcoch_k$ = function() {
        var tmp;
        if (this.index_1 < this.array_1.length) {
          var tmp$ret$0;
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          var tmp0_toUByte = this.array_1[tmp1];
          tmp$ret$0 = _UByte___init__impl__g9hnc4(tmp0_toUByte);
          tmp = tmp$ret$0;
        } else {
          throw NoSuchElementException_init_$Create$_0(this.index_1.toString());
        }
        return tmp;
      };
      Iterator.prototype.next_20eer_k$ = function() {
        return new UByte(this.next_mzcoch_k$());
      };
      Iterator.$metadata$ = classMeta("Iterator", [Iterator_3]);
      function UByteArray__contains_impl_njh19q($this, element) {
        var tmp = isObject3(new UByte(element)) ? new UByte(element) : THROW_CCE();
        if (!(tmp instanceof UByte))
          return false;
        var tmp_0 = _UByteArray___get_storage__impl__d4kctt($this);
        var tmp$ret$0;
        tmp$ret$0 = _UByte___get_data__impl__jof9qr(element);
        return contains_1(tmp_0, tmp$ret$0);
      }
      function UByteArray__contains_impl_njh19q_0($this, element) {
        if (!(element instanceof UByte))
          return false;
        var tmp = $this.storage_1;
        return UByteArray__contains_impl_njh19q(tmp, element instanceof UByte ? element.data_1 : THROW_CCE());
      }
      function UByteArray__containsAll_impl_v9s6dj($this, elements) {
        var tmp$ret$0;
        $l$block_0: {
          var tmp0_all = isInterface(elements, Collection) ? elements : THROW_CCE();
          var tmp;
          if (isInterface(tmp0_all, Collection)) {
            tmp = tmp0_all.isEmpty_y1axqb_k$();
          } else {
            tmp = false;
          }
          if (tmp) {
            tmp$ret$0 = true;
            break $l$block_0;
          }
          var tmp0_iterator = tmp0_all.iterator_jk1svi_k$();
          while (tmp0_iterator.hasNext_bitz1p_k$()) {
            var element = tmp0_iterator.next_20eer_k$();
            var tmp$ret$2;
            var tmp_0;
            if (element instanceof UByte) {
              var tmp_1 = _UByteArray___get_storage__impl__d4kctt($this);
              var tmp$ret$1;
              var tmp0_toByte = element.data_1;
              tmp$ret$1 = _UByte___get_data__impl__jof9qr(tmp0_toByte);
              tmp_0 = contains_1(tmp_1, tmp$ret$1);
            } else {
              tmp_0 = false;
            }
            tmp$ret$2 = tmp_0;
            if (!tmp$ret$2) {
              tmp$ret$0 = false;
              break $l$block_0;
            }
          }
          tmp$ret$0 = true;
        }
        return tmp$ret$0;
      }
      function UByteArray__containsAll_impl_v9s6dj_0($this, elements) {
        return UByteArray__containsAll_impl_v9s6dj($this.storage_1, elements);
      }
      function UByteArray__isEmpty_impl_nbfqsa($this) {
        return _UByteArray___get_storage__impl__d4kctt($this).length === 0;
      }
      function UByteArray__toString_impl_ukpl97($this) {
        return "UByteArray(storage=" + toString_1($this) + ")";
      }
      function UByteArray__hashCode_impl_ip8jx2($this) {
        return hashCode($this);
      }
      function UByteArray__equals_impl_roka4u($this, other) {
        if (!(other instanceof UByteArray))
          return false;
        var tmp0_other_with_cast = other instanceof UByteArray ? other.storage_1 : THROW_CCE();
        if (!equals($this, tmp0_other_with_cast))
          return false;
        return true;
      }
      function UByteArray(storage) {
        this.storage_1 = storage;
      }
      UByteArray.prototype.get_size_woubt6_k$ = function() {
        return _UByteArray___get_size__impl__h6pkdv(this.storage_1);
      };
      UByteArray.prototype.iterator_jk1svi_k$ = function() {
        return UByteArray__iterator_impl_509y1p(this.storage_1);
      };
      UByteArray.prototype.contains_6st81c_k$ = function(element) {
        return UByteArray__contains_impl_njh19q(this.storage_1, element);
      };
      UByteArray.prototype.contains_2ehdt1_k$ = function(element) {
        return UByteArray__contains_impl_njh19q_0(this, element);
      };
      UByteArray.prototype.containsAll_ymyv_k$ = function(elements) {
        return UByteArray__containsAll_impl_v9s6dj(this.storage_1, elements);
      };
      UByteArray.prototype.containsAll_jr3fla_k$ = function(elements) {
        return UByteArray__containsAll_impl_v9s6dj_0(this, elements);
      };
      UByteArray.prototype.isEmpty_y1axqb_k$ = function() {
        return UByteArray__isEmpty_impl_nbfqsa(this.storage_1);
      };
      UByteArray.prototype.toString = function() {
        return UByteArray__toString_impl_ukpl97(this.storage_1);
      };
      UByteArray.prototype.hashCode = function() {
        return UByteArray__hashCode_impl_ip8jx2(this.storage_1);
      };
      UByteArray.prototype.equals = function(other) {
        return UByteArray__equals_impl_roka4u(this.storage_1, other);
      };
      UByteArray.$metadata$ = classMeta("UByteArray", [Collection]);
      function _UInt___init__impl__l7qpdl(data) {
        return data;
      }
      function _UInt___get_data__impl__f0vqqw($this) {
        return $this;
      }
      function Companion_11() {
        Companion_instance_11 = this;
        this.MIN_VALUE_1 = _UInt___init__impl__l7qpdl(0);
        this.MAX_VALUE_1 = _UInt___init__impl__l7qpdl(-1);
        this.SIZE_BYTES_1 = 4;
        this.SIZE_BITS_1 = 32;
      }
      Companion_11.prototype.get_MIN_VALUE_9yzxs0_k$ = function() {
        return this.MIN_VALUE_1;
      };
      Companion_11.prototype.get_MAX_VALUE_blthzm_k$ = function() {
        return this.MAX_VALUE_1;
      };
      Companion_11.prototype.get_SIZE_BYTES_qphg4q_k$ = function() {
        return this.SIZE_BYTES_1;
      };
      Companion_11.prototype.get_SIZE_BITS_7qhjj9_k$ = function() {
        return this.SIZE_BITS_1;
      };
      Companion_11.$metadata$ = objectMeta("Companion");
      var Companion_instance_11;
      function Companion_getInstance_11() {
        if (Companion_instance_11 == null)
          new Companion_11();
        return Companion_instance_11;
      }
      function UInt__compareTo_impl_yacclj($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp0_compareTo = tmp$ret$0;
        tmp$ret$1 = uintCompare(_UInt___get_data__impl__f0vqqw($this), _UInt___get_data__impl__f0vqqw(tmp0_compareTo));
        return tmp$ret$1;
      }
      function UInt__compareTo_impl_yacclj_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp0_compareTo = tmp$ret$0;
        tmp$ret$1 = uintCompare(_UInt___get_data__impl__f0vqqw($this), _UInt___get_data__impl__f0vqqw(tmp0_compareTo));
        return tmp$ret$1;
      }
      function UInt__compareTo_impl_yacclj_1($this, other) {
        return uintCompare(_UInt___get_data__impl__f0vqqw($this), _UInt___get_data__impl__f0vqqw(other));
      }
      function UInt__compareTo_impl_yacclj_2($this, other) {
        var tmp = $this.data_1;
        return UInt__compareTo_impl_yacclj_1(tmp, other instanceof UInt ? other.data_1 : THROW_CCE());
      }
      function UInt__compareTo_impl_yacclj_3($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw($this)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_compareTo = tmp$ret$0;
        tmp$ret$1 = ulongCompare(_ULong___get_data__impl__fggpzb(tmp0_compareTo), _ULong___get_data__impl__fggpzb(other));
        return tmp$ret$1;
      }
      function UInt__plus_impl_gmhu6f($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp0_plus = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) + _UInt___get_data__impl__f0vqqw(tmp0_plus) | 0);
        return tmp$ret$1;
      }
      function UInt__plus_impl_gmhu6f_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp0_plus = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) + _UInt___get_data__impl__f0vqqw(tmp0_plus) | 0);
        return tmp$ret$1;
      }
      function UInt__plus_impl_gmhu6f_1($this, other) {
        return _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) + _UInt___get_data__impl__f0vqqw(other) | 0);
      }
      function UInt__plus_impl_gmhu6f_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw($this)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_plus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_plus).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(other)));
        return tmp$ret$1;
      }
      function UInt__minus_impl_c4dy1j($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp0_minus = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) - _UInt___get_data__impl__f0vqqw(tmp0_minus) | 0);
        return tmp$ret$1;
      }
      function UInt__minus_impl_c4dy1j_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp0_minus = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) - _UInt___get_data__impl__f0vqqw(tmp0_minus) | 0);
        return tmp$ret$1;
      }
      function UInt__minus_impl_c4dy1j_1($this, other) {
        return _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) - _UInt___get_data__impl__f0vqqw(other) | 0);
      }
      function UInt__minus_impl_c4dy1j_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw($this)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_minus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_minus).minus_llf5ei_k$(_ULong___get_data__impl__fggpzb(other)));
        return tmp$ret$1;
      }
      function UInt__times_impl_9tvds1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp0_times = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(imul(_UInt___get_data__impl__f0vqqw($this), _UInt___get_data__impl__f0vqqw(tmp0_times)));
        return tmp$ret$1;
      }
      function UInt__times_impl_9tvds1_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp0_times = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(imul(_UInt___get_data__impl__f0vqqw($this), _UInt___get_data__impl__f0vqqw(tmp0_times)));
        return tmp$ret$1;
      }
      function UInt__times_impl_9tvds1_1($this, other) {
        return _UInt___init__impl__l7qpdl(imul(_UInt___get_data__impl__f0vqqw($this), _UInt___get_data__impl__f0vqqw(other)));
      }
      function UInt__times_impl_9tvds1_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw($this)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_times = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_times).times_2zfqpc_k$(_ULong___get_data__impl__fggpzb(other)));
        return tmp$ret$1;
      }
      function UInt__div_impl_xkbbl6($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp0_div = tmp$ret$0;
        tmp$ret$1 = uintDivide($this, tmp0_div);
        return tmp$ret$1;
      }
      function UInt__div_impl_xkbbl6_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp0_div = tmp$ret$0;
        tmp$ret$1 = uintDivide($this, tmp0_div);
        return tmp$ret$1;
      }
      function UInt__div_impl_xkbbl6_1($this, other) {
        return uintDivide($this, other);
      }
      function UInt__div_impl_xkbbl6_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw($this)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_div = tmp$ret$0;
        tmp$ret$1 = ulongDivide(tmp0_div, other);
        return tmp$ret$1;
      }
      function UInt__rem_impl_muzcx9($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp0_rem = tmp$ret$0;
        tmp$ret$1 = uintRemainder($this, tmp0_rem);
        return tmp$ret$1;
      }
      function UInt__rem_impl_muzcx9_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp0_rem = tmp$ret$0;
        tmp$ret$1 = uintRemainder($this, tmp0_rem);
        return tmp$ret$1;
      }
      function UInt__rem_impl_muzcx9_1($this, other) {
        return uintRemainder($this, other);
      }
      function UInt__rem_impl_muzcx9_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw($this)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_rem = tmp$ret$0;
        tmp$ret$1 = ulongRemainder(tmp0_rem, other);
        return tmp$ret$1;
      }
      function UInt__floorDiv_impl_hg5qxa($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = uintDivide($this, tmp0_floorDiv);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UInt__floorDiv_impl_hg5qxa_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = uintDivide($this, tmp0_floorDiv);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UInt__floorDiv_impl_hg5qxa_1($this, other) {
        var tmp$ret$0;
        tmp$ret$0 = uintDivide($this, other);
        return tmp$ret$0;
      }
      function UInt__floorDiv_impl_hg5qxa_2($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw($this)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongDivide(tmp0_floorDiv, other);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UInt__mod_impl_l9f8at($this, other) {
        var tmp$ret$4;
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = uintRemainder($this, tmp0_mod);
        tmp$ret$2 = tmp$ret$1;
        var tmp2_toUByte = tmp$ret$2;
        var tmp$ret$3;
        var tmp1_toUByte = _UInt___get_data__impl__f0vqqw(tmp2_toUByte);
        tmp$ret$3 = _UByte___init__impl__g9hnc4(toByte(tmp1_toUByte));
        tmp$ret$4 = tmp$ret$3;
        return tmp$ret$4;
      }
      function UInt__mod_impl_l9f8at_0($this, other) {
        var tmp$ret$4;
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = uintRemainder($this, tmp0_mod);
        tmp$ret$2 = tmp$ret$1;
        var tmp2_toUShort = tmp$ret$2;
        var tmp$ret$3;
        var tmp1_toUShort = _UInt___get_data__impl__f0vqqw(tmp2_toUShort);
        tmp$ret$3 = _UShort___init__impl__jigrne(toShort(tmp1_toUShort));
        tmp$ret$4 = tmp$ret$3;
        return tmp$ret$4;
      }
      function UInt__mod_impl_l9f8at_1($this, other) {
        var tmp$ret$0;
        tmp$ret$0 = uintRemainder($this, other);
        return tmp$ret$0;
      }
      function UInt__mod_impl_l9f8at_2($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw($this)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongRemainder(tmp0_mod, other);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UInt__inc_impl_wvpje1($this) {
        return _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) + 1 | 0);
      }
      function UInt__dec_impl_u8n7zv($this) {
        return _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) - 1 | 0);
      }
      function UInt__rangeTo_impl_en5yc1($this, other) {
        return new UIntRange($this, other);
      }
      function UInt__shl_impl_o7n0a8($this, bitCount) {
        return _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) << bitCount);
      }
      function UInt__shr_impl_r1wqne($this, bitCount) {
        return _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) >>> bitCount | 0);
      }
      function UInt__and_impl_fv3j80($this, other) {
        return _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) & _UInt___get_data__impl__f0vqqw(other));
      }
      function UInt__or_impl_nrzdg0($this, other) {
        return _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) | _UInt___get_data__impl__f0vqqw(other));
      }
      function UInt__xor_impl_a7n4dw($this, other) {
        return _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw($this) ^ _UInt___get_data__impl__f0vqqw(other));
      }
      function UInt__inv_impl_t5jp3e($this) {
        return _UInt___init__impl__l7qpdl(~_UInt___get_data__impl__f0vqqw($this));
      }
      function UInt__toByte_impl_enbcz4($this) {
        return toByte(_UInt___get_data__impl__f0vqqw($this));
      }
      function UInt__toShort_impl_776xra($this) {
        return toShort(_UInt___get_data__impl__f0vqqw($this));
      }
      function UInt__toInt_impl_93yt4d($this) {
        return _UInt___get_data__impl__f0vqqw($this);
      }
      function UInt__toLong_impl_le5rq4($this) {
        return toLong(_UInt___get_data__impl__f0vqqw($this)).and_jhajnj_k$(new Long(-1, 0));
      }
      function UInt__toUByte_impl_qgjpt1($this) {
        var tmp$ret$0;
        var tmp0_toUByte = _UInt___get_data__impl__f0vqqw($this);
        tmp$ret$0 = _UByte___init__impl__g9hnc4(toByte(tmp0_toUByte));
        return tmp$ret$0;
      }
      function UInt__toUShort_impl_2yxcfl($this) {
        var tmp$ret$0;
        var tmp0_toUShort = _UInt___get_data__impl__f0vqqw($this);
        tmp$ret$0 = _UShort___init__impl__jigrne(toShort(tmp0_toUShort));
        return tmp$ret$0;
      }
      function UInt__toUInt_impl_cu5oym($this) {
        return $this;
      }
      function UInt__toULong_impl_8j37gv($this) {
        return _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw($this)).and_jhajnj_k$(new Long(-1, 0)));
      }
      function UInt__toFloat_impl_zijuyu($this) {
        var tmp$ret$0;
        tmp$ret$0 = uintToDouble(_UInt___get_data__impl__f0vqqw($this));
        return tmp$ret$0;
      }
      function UInt__toDouble_impl_f3ehy1($this) {
        return uintToDouble(_UInt___get_data__impl__f0vqqw($this));
      }
      function UInt__toString_impl_dbgl21($this) {
        var tmp$ret$0;
        tmp$ret$0 = toLong(_UInt___get_data__impl__f0vqqw($this)).and_jhajnj_k$(new Long(-1, 0));
        return tmp$ret$0.toString();
      }
      function UInt__hashCode_impl_z2mhuw($this) {
        return $this;
      }
      function UInt__equals_impl_ffdoxg($this, other) {
        if (!(other instanceof UInt))
          return false;
        var tmp0_other_with_cast = other instanceof UInt ? other.data_1 : THROW_CCE();
        if (!($this === tmp0_other_with_cast))
          return false;
        return true;
      }
      function UInt(data) {
        Companion_getInstance_11();
        this.data_1 = data;
      }
      UInt.prototype.compareTo_n4kp7s_k$ = function(other) {
        return UInt__compareTo_impl_yacclj_1(this.data_1, other);
      };
      UInt.prototype.compareTo_6thzaj_k$ = function(other) {
        return UInt__compareTo_impl_yacclj_2(this, other);
      };
      UInt.prototype.toString = function() {
        return UInt__toString_impl_dbgl21(this.data_1);
      };
      UInt.prototype.hashCode = function() {
        return UInt__hashCode_impl_z2mhuw(this.data_1);
      };
      UInt.prototype.equals = function(other) {
        return UInt__equals_impl_ffdoxg(this.data_1, other);
      };
      UInt.$metadata$ = classMeta("UInt", [Comparable]);
      function toUInt(_this__u8e3s4) {
        return _UInt___init__impl__l7qpdl(_this__u8e3s4.toInt_1tsl84_k$());
      }
      function toUInt_0(_this__u8e3s4) {
        return _UInt___init__impl__l7qpdl(_this__u8e3s4);
      }
      function toUInt_1(_this__u8e3s4) {
        return _UInt___init__impl__l7qpdl(_this__u8e3s4);
      }
      function toUInt_2(_this__u8e3s4) {
        return doubleToUInt(_this__u8e3s4);
      }
      function toUInt_3(_this__u8e3s4) {
        return doubleToUInt(_this__u8e3s4);
      }
      function toUInt_4(_this__u8e3s4) {
        return _UInt___init__impl__l7qpdl(_this__u8e3s4);
      }
      function _get_array__jslnqg_0($this) {
        return $this.array_1;
      }
      function _set_index__fyfqnn_0($this, _set____db54di) {
        $this.index_1 = _set____db54di;
      }
      function _get_index__g2optt_0($this) {
        return $this.index_1;
      }
      function _UIntArray___init__impl__ghjpc6(storage) {
        return storage;
      }
      function _UIntArray___get_storage__impl__92a0v0($this) {
        return $this;
      }
      function _UIntArray___init__impl__ghjpc6_0(size2) {
        var tmp = _UIntArray___init__impl__ghjpc6(new Int32Array(size2));
        return tmp;
      }
      function UIntArray__get_impl_gp5kza($this, index) {
        var tmp$ret$0;
        var tmp0_toUInt = _UIntArray___get_storage__impl__92a0v0($this)[index];
        tmp$ret$0 = _UInt___init__impl__l7qpdl(tmp0_toUInt);
        return tmp$ret$0;
      }
      function UIntArray__set_impl_7f2zu2($this, index, value) {
        var tmp = _UIntArray___get_storage__impl__92a0v0($this);
        var tmp$ret$0;
        tmp$ret$0 = _UInt___get_data__impl__f0vqqw(value);
        tmp[index] = tmp$ret$0;
      }
      function _UIntArray___get_size__impl__r6l8ci($this) {
        return _UIntArray___get_storage__impl__92a0v0($this).length;
      }
      function UIntArray__iterator_impl_tkdv7k($this) {
        return new Iterator_0(_UIntArray___get_storage__impl__92a0v0($this));
      }
      function Iterator_0(array3) {
        this.array_1 = array3;
        this.index_1 = 0;
      }
      Iterator_0.prototype.hasNext_bitz1p_k$ = function() {
        return this.index_1 < this.array_1.length;
      };
      Iterator_0.prototype.next_3167jc_k$ = function() {
        var tmp;
        if (this.index_1 < this.array_1.length) {
          var tmp$ret$0;
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          var tmp0_toUInt = this.array_1[tmp1];
          tmp$ret$0 = _UInt___init__impl__l7qpdl(tmp0_toUInt);
          tmp = tmp$ret$0;
        } else {
          throw NoSuchElementException_init_$Create$_0(this.index_1.toString());
        }
        return tmp;
      };
      Iterator_0.prototype.next_20eer_k$ = function() {
        return new UInt(this.next_3167jc_k$());
      };
      Iterator_0.$metadata$ = classMeta("Iterator", [Iterator_3]);
      function UIntArray__contains_impl_b16rzj($this, element) {
        var tmp = isObject3(new UInt(element)) ? new UInt(element) : THROW_CCE();
        if (!(tmp instanceof UInt))
          return false;
        var tmp_0 = _UIntArray___get_storage__impl__92a0v0($this);
        var tmp$ret$0;
        tmp$ret$0 = _UInt___get_data__impl__f0vqqw(element);
        return contains_3(tmp_0, tmp$ret$0);
      }
      function UIntArray__contains_impl_b16rzj_0($this, element) {
        if (!(element instanceof UInt))
          return false;
        var tmp = $this.storage_1;
        return UIntArray__contains_impl_b16rzj(tmp, element instanceof UInt ? element.data_1 : THROW_CCE());
      }
      function UIntArray__containsAll_impl_414g22($this, elements) {
        var tmp$ret$0;
        $l$block_0: {
          var tmp0_all = isInterface(elements, Collection) ? elements : THROW_CCE();
          var tmp;
          if (isInterface(tmp0_all, Collection)) {
            tmp = tmp0_all.isEmpty_y1axqb_k$();
          } else {
            tmp = false;
          }
          if (tmp) {
            tmp$ret$0 = true;
            break $l$block_0;
          }
          var tmp0_iterator = tmp0_all.iterator_jk1svi_k$();
          while (tmp0_iterator.hasNext_bitz1p_k$()) {
            var element = tmp0_iterator.next_20eer_k$();
            var tmp$ret$2;
            var tmp_0;
            if (element instanceof UInt) {
              var tmp_1 = _UIntArray___get_storage__impl__92a0v0($this);
              var tmp$ret$1;
              var tmp0_toInt = element.data_1;
              tmp$ret$1 = _UInt___get_data__impl__f0vqqw(tmp0_toInt);
              tmp_0 = contains_3(tmp_1, tmp$ret$1);
            } else {
              tmp_0 = false;
            }
            tmp$ret$2 = tmp_0;
            if (!tmp$ret$2) {
              tmp$ret$0 = false;
              break $l$block_0;
            }
          }
          tmp$ret$0 = true;
        }
        return tmp$ret$0;
      }
      function UIntArray__containsAll_impl_414g22_0($this, elements) {
        return UIntArray__containsAll_impl_414g22($this.storage_1, elements);
      }
      function UIntArray__isEmpty_impl_vd8j4n($this) {
        return _UIntArray___get_storage__impl__92a0v0($this).length === 0;
      }
      function UIntArray__toString_impl_3zy802($this) {
        return "UIntArray(storage=" + toString_1($this) + ")";
      }
      function UIntArray__hashCode_impl_hr7ost($this) {
        return hashCode($this);
      }
      function UIntArray__equals_impl_flcmof($this, other) {
        if (!(other instanceof UIntArray))
          return false;
        var tmp0_other_with_cast = other instanceof UIntArray ? other.storage_1 : THROW_CCE();
        if (!equals($this, tmp0_other_with_cast))
          return false;
        return true;
      }
      function UIntArray(storage) {
        this.storage_1 = storage;
      }
      UIntArray.prototype.get_size_woubt6_k$ = function() {
        return _UIntArray___get_size__impl__r6l8ci(this.storage_1);
      };
      UIntArray.prototype.iterator_jk1svi_k$ = function() {
        return UIntArray__iterator_impl_tkdv7k(this.storage_1);
      };
      UIntArray.prototype.contains_i3zyt5_k$ = function(element) {
        return UIntArray__contains_impl_b16rzj(this.storage_1, element);
      };
      UIntArray.prototype.contains_2ehdt1_k$ = function(element) {
        return UIntArray__contains_impl_b16rzj_0(this, element);
      };
      UIntArray.prototype.containsAll_ts90z8_k$ = function(elements) {
        return UIntArray__containsAll_impl_414g22(this.storage_1, elements);
      };
      UIntArray.prototype.containsAll_jr3fla_k$ = function(elements) {
        return UIntArray__containsAll_impl_414g22_0(this, elements);
      };
      UIntArray.prototype.isEmpty_y1axqb_k$ = function() {
        return UIntArray__isEmpty_impl_vd8j4n(this.storage_1);
      };
      UIntArray.prototype.toString = function() {
        return UIntArray__toString_impl_3zy802(this.storage_1);
      };
      UIntArray.prototype.hashCode = function() {
        return UIntArray__hashCode_impl_hr7ost(this.storage_1);
      };
      UIntArray.prototype.equals = function(other) {
        return UIntArray__equals_impl_flcmof(this.storage_1, other);
      };
      UIntArray.$metadata$ = classMeta("UIntArray", [Collection]);
      function Companion_12() {
        Companion_instance_12 = this;
        var tmp = this;
        Companion_getInstance_11();
        var tmp_0 = _UInt___init__impl__l7qpdl(-1);
        Companion_getInstance_11();
        tmp.EMPTY_1 = new UIntRange(tmp_0, _UInt___init__impl__l7qpdl(0));
      }
      Companion_12.prototype.get_EMPTY_i8q41w_k$ = function() {
        return this.EMPTY_1;
      };
      Companion_12.$metadata$ = objectMeta("Companion");
      var Companion_instance_12;
      function Companion_getInstance_12() {
        if (Companion_instance_12 == null)
          new Companion_12();
        return Companion_instance_12;
      }
      function UIntRange(start2, endInclusive) {
        Companion_getInstance_12();
        UIntProgression.call(this, start2, endInclusive, 1);
      }
      UIntRange.prototype.get_start_qjckny_k$ = function() {
        return this.first_1;
      };
      UIntRange.prototype.get_start_iypx6h_k$ = function() {
        return new UInt(this.get_start_qjckny_k$());
      };
      UIntRange.prototype.get_endInclusive_oo5uyp_k$ = function() {
        return this.last_1;
      };
      UIntRange.prototype.get_endInclusive_r07xpi_k$ = function() {
        return new UInt(this.get_endInclusive_oo5uyp_k$());
      };
      UIntRange.prototype.get_endExclusive_umnfld_k$ = function() {
        var tmp = new UInt(this.last_1);
        Companion_getInstance_11();
        if (equals(tmp, new UInt(_UInt___init__impl__l7qpdl(-1)))) {
          throw IllegalStateException_init_$Create$_0("Cannot return the exclusive upper bound of a range that includes MAX_VALUE.");
        }
        var tmp$ret$0;
        var tmp0_plus = this.last_1;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_plus) + _UInt___get_data__impl__f0vqqw(_UInt___init__impl__l7qpdl(1)) | 0);
        return tmp$ret$0;
      };
      UIntRange.prototype.get_endExclusive_pmwm6k_k$ = function() {
        return new UInt(this.get_endExclusive_umnfld_k$());
      };
      UIntRange.prototype.contains_i3zyt5_k$ = function(value) {
        var tmp;
        var tmp$ret$0;
        var tmp0_compareTo = this.first_1;
        tmp$ret$0 = uintCompare(_UInt___get_data__impl__f0vqqw(tmp0_compareTo), _UInt___get_data__impl__f0vqqw(value));
        if (tmp$ret$0 <= 0) {
          var tmp$ret$1;
          var tmp1_compareTo = this.last_1;
          tmp$ret$1 = uintCompare(_UInt___get_data__impl__f0vqqw(value), _UInt___get_data__impl__f0vqqw(tmp1_compareTo));
          tmp = tmp$ret$1 <= 0;
        } else {
          tmp = false;
        }
        return tmp;
      };
      UIntRange.prototype.contains_2ehdtg_k$ = function(value) {
        return this.contains_i3zyt5_k$(value instanceof UInt ? value.data_1 : THROW_CCE());
      };
      UIntRange.prototype.isEmpty_y1axqb_k$ = function() {
        var tmp$ret$0;
        var tmp0_compareTo = this.first_1;
        var tmp1_compareTo = this.last_1;
        tmp$ret$0 = uintCompare(_UInt___get_data__impl__f0vqqw(tmp0_compareTo), _UInt___get_data__impl__f0vqqw(tmp1_compareTo));
        return tmp$ret$0 > 0;
      };
      UIntRange.prototype.equals = function(other) {
        var tmp;
        if (other instanceof UIntRange) {
          tmp = (this.isEmpty_y1axqb_k$() ? other.isEmpty_y1axqb_k$() : false) ? true : this.first_1 === other.first_1 ? this.last_1 === other.last_1 : false;
        } else {
          tmp = false;
        }
        return tmp;
      };
      UIntRange.prototype.hashCode = function() {
        var tmp;
        if (this.isEmpty_y1axqb_k$()) {
          tmp = -1;
        } else {
          var tmp$ret$0;
          var tmp0_toInt = this.first_1;
          tmp$ret$0 = _UInt___get_data__impl__f0vqqw(tmp0_toInt);
          var tmp_0 = imul(31, tmp$ret$0);
          var tmp$ret$1;
          var tmp1_toInt = this.last_1;
          tmp$ret$1 = _UInt___get_data__impl__f0vqqw(tmp1_toInt);
          tmp = tmp_0 + tmp$ret$1 | 0;
        }
        return tmp;
      };
      UIntRange.prototype.toString = function() {
        return "" + new UInt(this.first_1) + ".." + new UInt(this.last_1);
      };
      UIntRange.$metadata$ = classMeta("UIntRange", [ClosedRange, OpenEndRange], void 0, void 0, void 0, UIntProgression.prototype);
      function Companion_13() {
        Companion_instance_13 = this;
      }
      Companion_13.prototype.fromClosedRange_nl90ve_k$ = function(rangeStart, rangeEnd, step) {
        return new UIntProgression(rangeStart, rangeEnd, step);
      };
      Companion_13.$metadata$ = objectMeta("Companion");
      var Companion_instance_13;
      function Companion_getInstance_13() {
        if (Companion_instance_13 == null)
          new Companion_13();
        return Companion_instance_13;
      }
      function UIntProgression(start2, endInclusive, step) {
        Companion_getInstance_13();
        if (step === 0)
          throw IllegalArgumentException_init_$Create$_0("Step must be non-zero.");
        if (step === IntCompanionObject_getInstance().MIN_VALUE_1)
          throw IllegalArgumentException_init_$Create$_0("Step must be greater than Int.MIN_VALUE to avoid overflow on negation.");
        this.first_1 = start2;
        this.last_1 = getProgressionLastElement_1(start2, endInclusive, step);
        this.step_1 = step;
      }
      UIntProgression.prototype.get_first_englpo_k$ = function() {
        return this.first_1;
      };
      UIntProgression.prototype.get_last_rpcnd0_k$ = function() {
        return this.last_1;
      };
      UIntProgression.prototype.get_step_woujh1_k$ = function() {
        return this.step_1;
      };
      UIntProgression.prototype.iterator_jk1svi_k$ = function() {
        return new UIntProgressionIterator(this.first_1, this.last_1, this.step_1);
      };
      UIntProgression.prototype.isEmpty_y1axqb_k$ = function() {
        var tmp;
        if (this.step_1 > 0) {
          var tmp$ret$0;
          var tmp0_compareTo = this.first_1;
          var tmp1_compareTo = this.last_1;
          tmp$ret$0 = uintCompare(_UInt___get_data__impl__f0vqqw(tmp0_compareTo), _UInt___get_data__impl__f0vqqw(tmp1_compareTo));
          tmp = tmp$ret$0 > 0;
        } else {
          var tmp$ret$1;
          var tmp2_compareTo = this.first_1;
          var tmp3_compareTo = this.last_1;
          tmp$ret$1 = uintCompare(_UInt___get_data__impl__f0vqqw(tmp2_compareTo), _UInt___get_data__impl__f0vqqw(tmp3_compareTo));
          tmp = tmp$ret$1 < 0;
        }
        return tmp;
      };
      UIntProgression.prototype.equals = function(other) {
        var tmp;
        if (other instanceof UIntProgression) {
          tmp = (this.isEmpty_y1axqb_k$() ? other.isEmpty_y1axqb_k$() : false) ? true : (this.first_1 === other.first_1 ? this.last_1 === other.last_1 : false) ? this.step_1 === other.step_1 : false;
        } else {
          tmp = false;
        }
        return tmp;
      };
      UIntProgression.prototype.hashCode = function() {
        var tmp;
        if (this.isEmpty_y1axqb_k$()) {
          tmp = -1;
        } else {
          var tmp$ret$0;
          var tmp0_toInt = this.first_1;
          tmp$ret$0 = _UInt___get_data__impl__f0vqqw(tmp0_toInt);
          var tmp_0 = imul(31, tmp$ret$0);
          var tmp$ret$1;
          var tmp1_toInt = this.last_1;
          tmp$ret$1 = _UInt___get_data__impl__f0vqqw(tmp1_toInt);
          tmp = imul(31, tmp_0 + tmp$ret$1 | 0) + this.step_1 | 0;
        }
        return tmp;
      };
      UIntProgression.prototype.toString = function() {
        return this.step_1 > 0 ? "" + new UInt(this.first_1) + ".." + new UInt(this.last_1) + " step " + this.step_1 : "" + new UInt(this.first_1) + " downTo " + new UInt(this.last_1) + " step " + (-this.step_1 | 0);
      };
      UIntProgression.$metadata$ = classMeta("UIntProgression", [Iterable]);
      function _get_finalElement__gc6m3p_2($this) {
        return $this.finalElement_1;
      }
      function _set_hasNext__86v2bs_2($this, _set____db54di) {
        $this.hasNext_1 = _set____db54di;
      }
      function _get_hasNext__xt3cos_2($this) {
        return $this.hasNext_1;
      }
      function _get_step__ddv2tb($this) {
        return $this.step_1;
      }
      function _set_next__9r2xms_2($this, _set____db54di) {
        $this.next_1 = _set____db54di;
      }
      function _get_next__daux88_2($this) {
        return $this.next_1;
      }
      function UIntProgressionIterator(first, last, step) {
        this.finalElement_1 = last;
        var tmp = this;
        var tmp_0;
        if (step > 0) {
          var tmp$ret$0;
          tmp$ret$0 = uintCompare(_UInt___get_data__impl__f0vqqw(first), _UInt___get_data__impl__f0vqqw(last));
          tmp_0 = tmp$ret$0 <= 0;
        } else {
          var tmp$ret$1;
          tmp$ret$1 = uintCompare(_UInt___get_data__impl__f0vqqw(first), _UInt___get_data__impl__f0vqqw(last));
          tmp_0 = tmp$ret$1 >= 0;
        }
        tmp.hasNext_1 = tmp_0;
        var tmp_1 = this;
        var tmp$ret$2;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(step);
        tmp_1.step_1 = tmp$ret$2;
        this.next_1 = this.hasNext_1 ? first : this.finalElement_1;
      }
      UIntProgressionIterator.prototype.hasNext_bitz1p_k$ = function() {
        return this.hasNext_1;
      };
      UIntProgressionIterator.prototype.next_3167jc_k$ = function() {
        var value = this.next_1;
        if (value === this.finalElement_1) {
          if (!this.hasNext_1)
            throw NoSuchElementException_init_$Create$();
          this.hasNext_1 = false;
        } else {
          var tmp0_this = this;
          var tmp = tmp0_this;
          var tmp$ret$0;
          var tmp0_plus = tmp0_this.next_1;
          var tmp1_plus = this.step_1;
          tmp$ret$0 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_plus) + _UInt___get_data__impl__f0vqqw(tmp1_plus) | 0);
          tmp.next_1 = tmp$ret$0;
        }
        return value;
      };
      UIntProgressionIterator.prototype.next_20eer_k$ = function() {
        return new UInt(this.next_3167jc_k$());
      };
      UIntProgressionIterator.$metadata$ = classMeta("UIntProgressionIterator", [Iterator_3]);
      function _ULong___init__impl__c78o9k(data) {
        return data;
      }
      function _ULong___get_data__impl__fggpzb($this) {
        return $this;
      }
      function Companion_14() {
        Companion_instance_14 = this;
        this.MIN_VALUE_1 = _ULong___init__impl__c78o9k(new Long(0, 0));
        this.MAX_VALUE_1 = _ULong___init__impl__c78o9k(new Long(-1, -1));
        this.SIZE_BYTES_1 = 8;
        this.SIZE_BITS_1 = 64;
      }
      Companion_14.prototype.get_MIN_VALUE_p0jsuj_k$ = function() {
        return this.MIN_VALUE_1;
      };
      Companion_14.prototype.get_MAX_VALUE_4mw5fd_k$ = function() {
        return this.MAX_VALUE_1;
      };
      Companion_14.prototype.get_SIZE_BYTES_qphg4q_k$ = function() {
        return this.SIZE_BYTES_1;
      };
      Companion_14.prototype.get_SIZE_BITS_7qhjj9_k$ = function() {
        return this.SIZE_BITS_1;
      };
      Companion_14.$metadata$ = objectMeta("Companion");
      var Companion_instance_14;
      function Companion_getInstance_14() {
        if (Companion_instance_14 == null)
          new Companion_14();
        return Companion_instance_14;
      }
      function ULong__compareTo_impl_38i7tu($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr(other)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_compareTo = tmp$ret$0;
        tmp$ret$1 = ulongCompare(_ULong___get_data__impl__fggpzb($this), _ULong___get_data__impl__fggpzb(tmp0_compareTo));
        return tmp$ret$1;
      }
      function ULong__compareTo_impl_38i7tu_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245(other)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_compareTo = tmp$ret$0;
        tmp$ret$1 = ulongCompare(_ULong___get_data__impl__fggpzb($this), _ULong___get_data__impl__fggpzb(tmp0_compareTo));
        return tmp$ret$1;
      }
      function ULong__compareTo_impl_38i7tu_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw(other)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_compareTo = tmp$ret$0;
        tmp$ret$1 = ulongCompare(_ULong___get_data__impl__fggpzb($this), _ULong___get_data__impl__fggpzb(tmp0_compareTo));
        return tmp$ret$1;
      }
      function ULong__compareTo_impl_38i7tu_2($this, other) {
        return ulongCompare(_ULong___get_data__impl__fggpzb($this), _ULong___get_data__impl__fggpzb(other));
      }
      function ULong__compareTo_impl_38i7tu_3($this, other) {
        var tmp = $this.data_1;
        return ULong__compareTo_impl_38i7tu_2(tmp, other instanceof ULong ? other.data_1 : THROW_CCE());
      }
      function ULong__plus_impl_plxuny($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr(other)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_plus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(tmp0_plus)));
        return tmp$ret$1;
      }
      function ULong__plus_impl_plxuny_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245(other)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_plus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(tmp0_plus)));
        return tmp$ret$1;
      }
      function ULong__plus_impl_plxuny_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw(other)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_plus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(tmp0_plus)));
        return tmp$ret$1;
      }
      function ULong__plus_impl_plxuny_2($this, other) {
        return _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(other)));
      }
      function ULong__minus_impl_hq1qum($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr(other)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_minus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).minus_llf5ei_k$(_ULong___get_data__impl__fggpzb(tmp0_minus)));
        return tmp$ret$1;
      }
      function ULong__minus_impl_hq1qum_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245(other)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_minus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).minus_llf5ei_k$(_ULong___get_data__impl__fggpzb(tmp0_minus)));
        return tmp$ret$1;
      }
      function ULong__minus_impl_hq1qum_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw(other)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_minus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).minus_llf5ei_k$(_ULong___get_data__impl__fggpzb(tmp0_minus)));
        return tmp$ret$1;
      }
      function ULong__minus_impl_hq1qum_2($this, other) {
        return _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).minus_llf5ei_k$(_ULong___get_data__impl__fggpzb(other)));
      }
      function ULong__times_impl_ffj6l4($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr(other)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_times = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).times_2zfqpc_k$(_ULong___get_data__impl__fggpzb(tmp0_times)));
        return tmp$ret$1;
      }
      function ULong__times_impl_ffj6l4_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245(other)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_times = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).times_2zfqpc_k$(_ULong___get_data__impl__fggpzb(tmp0_times)));
        return tmp$ret$1;
      }
      function ULong__times_impl_ffj6l4_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw(other)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_times = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).times_2zfqpc_k$(_ULong___get_data__impl__fggpzb(tmp0_times)));
        return tmp$ret$1;
      }
      function ULong__times_impl_ffj6l4_2($this, other) {
        return _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).times_2zfqpc_k$(_ULong___get_data__impl__fggpzb(other)));
      }
      function ULong__div_impl_iugpv1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr(other)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_div = tmp$ret$0;
        tmp$ret$1 = ulongDivide($this, tmp0_div);
        return tmp$ret$1;
      }
      function ULong__div_impl_iugpv1_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245(other)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_div = tmp$ret$0;
        tmp$ret$1 = ulongDivide($this, tmp0_div);
        return tmp$ret$1;
      }
      function ULong__div_impl_iugpv1_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw(other)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_div = tmp$ret$0;
        tmp$ret$1 = ulongDivide($this, tmp0_div);
        return tmp$ret$1;
      }
      function ULong__div_impl_iugpv1_2($this, other) {
        return ulongDivide($this, other);
      }
      function ULong__rem_impl_48ncec($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr(other)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_rem = tmp$ret$0;
        tmp$ret$1 = ulongRemainder($this, tmp0_rem);
        return tmp$ret$1;
      }
      function ULong__rem_impl_48ncec_0($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245(other)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_rem = tmp$ret$0;
        tmp$ret$1 = ulongRemainder($this, tmp0_rem);
        return tmp$ret$1;
      }
      function ULong__rem_impl_48ncec_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw(other)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_rem = tmp$ret$0;
        tmp$ret$1 = ulongRemainder($this, tmp0_rem);
        return tmp$ret$1;
      }
      function ULong__rem_impl_48ncec_2($this, other) {
        return ulongRemainder($this, other);
      }
      function ULong__floorDiv_impl_p06vs9($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr(other)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongDivide($this, tmp0_floorDiv);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function ULong__floorDiv_impl_p06vs9_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245(other)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongDivide($this, tmp0_floorDiv);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function ULong__floorDiv_impl_p06vs9_1($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw(other)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongDivide($this, tmp0_floorDiv);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function ULong__floorDiv_impl_p06vs9_2($this, other) {
        var tmp$ret$0;
        tmp$ret$0 = ulongDivide($this, other);
        return tmp$ret$0;
      }
      function ULong__mod_impl_2n37rw($this, other) {
        var tmp$ret$4;
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UByte___get_data__impl__jof9qr(other)).and_jhajnj_k$(new Long(255, 0)));
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongRemainder($this, tmp0_mod);
        tmp$ret$2 = tmp$ret$1;
        var tmp2_toUByte = tmp$ret$2;
        var tmp$ret$3;
        var tmp1_toUByte = _ULong___get_data__impl__fggpzb(tmp2_toUByte);
        tmp$ret$3 = _UByte___init__impl__g9hnc4(tmp1_toUByte.toByte_edm0nx_k$());
        tmp$ret$4 = tmp$ret$3;
        return tmp$ret$4;
      }
      function ULong__mod_impl_2n37rw_0($this, other) {
        var tmp$ret$4;
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245(other)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongRemainder($this, tmp0_mod);
        tmp$ret$2 = tmp$ret$1;
        var tmp2_toUShort = tmp$ret$2;
        var tmp$ret$3;
        var tmp1_toUShort = _ULong___get_data__impl__fggpzb(tmp2_toUShort);
        tmp$ret$3 = _UShort___init__impl__jigrne(tmp1_toUShort.toShort_ja8oqn_k$());
        tmp$ret$4 = tmp$ret$3;
        return tmp$ret$4;
      }
      function ULong__mod_impl_2n37rw_1($this, other) {
        var tmp$ret$4;
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw(other)).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongRemainder($this, tmp0_mod);
        tmp$ret$2 = tmp$ret$1;
        var tmp2_toUInt = tmp$ret$2;
        var tmp$ret$3;
        var tmp1_toUInt = _ULong___get_data__impl__fggpzb(tmp2_toUInt);
        tmp$ret$3 = _UInt___init__impl__l7qpdl(tmp1_toUInt.toInt_1tsl84_k$());
        tmp$ret$4 = tmp$ret$3;
        return tmp$ret$4;
      }
      function ULong__mod_impl_2n37rw_2($this, other) {
        var tmp$ret$0;
        tmp$ret$0 = ulongRemainder($this, other);
        return tmp$ret$0;
      }
      function ULong__inc_impl_e9div4($this) {
        return _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).inc_28ke_k$());
      }
      function ULong__dec_impl_m64tgc($this) {
        return _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).dec_24n6_k$());
      }
      function ULong__rangeTo_impl_tre43e($this, other) {
        return new ULongRange($this, other);
      }
      function ULong__shl_impl_5lazrb($this, bitCount) {
        return _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).shl_po5ip6_k$(bitCount));
      }
      function ULong__shr_impl_8fkq4h($this, bitCount) {
        return _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).ushr_rr8rvr_k$(bitCount));
      }
      function ULong__and_impl_2r8hax($this, other) {
        return _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).and_jhajnj_k$(_ULong___get_data__impl__fggpzb(other)));
      }
      function ULong__or_impl_mne2xz($this, other) {
        return _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).or_s401rn_k$(_ULong___get_data__impl__fggpzb(other)));
      }
      function ULong__xor_impl_stz4wt($this, other) {
        return _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).xor_jjua9n_k$(_ULong___get_data__impl__fggpzb(other)));
      }
      function ULong__inv_impl_n98cct($this) {
        return _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb($this).inv_28kx_k$());
      }
      function ULong__toByte_impl_gxyc49($this) {
        return _ULong___get_data__impl__fggpzb($this).toByte_edm0nx_k$();
      }
      function ULong__toShort_impl_7x1803($this) {
        return _ULong___get_data__impl__fggpzb($this).toShort_ja8oqn_k$();
      }
      function ULong__toInt_impl_3ib0ba($this) {
        return _ULong___get_data__impl__fggpzb($this).toInt_1tsl84_k$();
      }
      function ULong__toLong_impl_i1ol5n($this) {
        return _ULong___get_data__impl__fggpzb($this);
      }
      function ULong__toUByte_impl_bcbk1o($this) {
        var tmp$ret$0;
        var tmp0_toUByte = _ULong___get_data__impl__fggpzb($this);
        tmp$ret$0 = _UByte___init__impl__g9hnc4(tmp0_toUByte.toByte_edm0nx_k$());
        return tmp$ret$0;
      }
      function ULong__toUShort_impl_vjorp6($this) {
        var tmp$ret$0;
        var tmp0_toUShort = _ULong___get_data__impl__fggpzb($this);
        tmp$ret$0 = _UShort___init__impl__jigrne(tmp0_toUShort.toShort_ja8oqn_k$());
        return tmp$ret$0;
      }
      function ULong__toUInt_impl_qlonx5($this) {
        var tmp$ret$0;
        var tmp0_toUInt = _ULong___get_data__impl__fggpzb($this);
        tmp$ret$0 = _UInt___init__impl__l7qpdl(tmp0_toUInt.toInt_1tsl84_k$());
        return tmp$ret$0;
      }
      function ULong__toULong_impl_nnbd88($this) {
        return $this;
      }
      function ULong__toFloat_impl_kebp7h($this) {
        var tmp$ret$0;
        tmp$ret$0 = ulongToDouble(_ULong___get_data__impl__fggpzb($this));
        return tmp$ret$0;
      }
      function ULong__toDouble_impl_dhcxbk($this) {
        return ulongToDouble(_ULong___get_data__impl__fggpzb($this));
      }
      function ULong__toString_impl_f9au7k($this) {
        return ulongToString(_ULong___get_data__impl__fggpzb($this));
      }
      function ULong__hashCode_impl_6hv2lb($this) {
        return $this.hashCode();
      }
      function ULong__equals_impl_o0gnyb($this, other) {
        if (!(other instanceof ULong))
          return false;
        var tmp0_other_with_cast = other instanceof ULong ? other.data_1 : THROW_CCE();
        if (!$this.equals(tmp0_other_with_cast))
          return false;
        return true;
      }
      function ULong(data) {
        Companion_getInstance_14();
        this.data_1 = data;
      }
      ULong.prototype.compareTo_6mr3kz_k$ = function(other) {
        return ULong__compareTo_impl_38i7tu_2(this.data_1, other);
      };
      ULong.prototype.compareTo_6thzaj_k$ = function(other) {
        return ULong__compareTo_impl_38i7tu_3(this, other);
      };
      ULong.prototype.toString = function() {
        return ULong__toString_impl_f9au7k(this.data_1);
      };
      ULong.prototype.hashCode = function() {
        return ULong__hashCode_impl_6hv2lb(this.data_1);
      };
      ULong.prototype.equals = function(other) {
        return ULong__equals_impl_o0gnyb(this.data_1, other);
      };
      ULong.$metadata$ = classMeta("ULong", [Comparable]);
      function toULong(_this__u8e3s4) {
        return _ULong___init__impl__c78o9k(_this__u8e3s4);
      }
      function toULong_0(_this__u8e3s4) {
        return _ULong___init__impl__c78o9k(toLong(_this__u8e3s4));
      }
      function toULong_1(_this__u8e3s4) {
        return doubleToULong(_this__u8e3s4);
      }
      function toULong_2(_this__u8e3s4) {
        return doubleToULong(_this__u8e3s4);
      }
      function toULong_3(_this__u8e3s4) {
        return _ULong___init__impl__c78o9k(toLong(_this__u8e3s4));
      }
      function toULong_4(_this__u8e3s4) {
        return _ULong___init__impl__c78o9k(toLong(_this__u8e3s4));
      }
      function _get_array__jslnqg_1($this) {
        return $this.array_1;
      }
      function _set_index__fyfqnn_1($this, _set____db54di) {
        $this.index_1 = _set____db54di;
      }
      function _get_index__g2optt_1($this) {
        return $this.index_1;
      }
      function _ULongArray___init__impl__twm1l3(storage) {
        return storage;
      }
      function _ULongArray___get_storage__impl__28e64j($this) {
        return $this;
      }
      function _ULongArray___init__impl__twm1l3_0(size2) {
        var tmp = _ULongArray___init__impl__twm1l3(longArray(size2));
        return tmp;
      }
      function ULongArray__get_impl_pr71q9($this, index) {
        var tmp$ret$0;
        var tmp0_toULong = _ULongArray___get_storage__impl__28e64j($this)[index];
        tmp$ret$0 = _ULong___init__impl__c78o9k(tmp0_toULong);
        return tmp$ret$0;
      }
      function ULongArray__set_impl_z19mvh($this, index, value) {
        var tmp = _ULongArray___get_storage__impl__28e64j($this);
        var tmp$ret$0;
        tmp$ret$0 = _ULong___get_data__impl__fggpzb(value);
        tmp[index] = tmp$ret$0;
      }
      function _ULongArray___get_size__impl__ju6dtr($this) {
        return _ULongArray___get_storage__impl__28e64j($this).length;
      }
      function ULongArray__iterator_impl_cq4d2h($this) {
        return new Iterator_1(_ULongArray___get_storage__impl__28e64j($this));
      }
      function Iterator_1(array3) {
        this.array_1 = array3;
        this.index_1 = 0;
      }
      Iterator_1.prototype.hasNext_bitz1p_k$ = function() {
        return this.index_1 < this.array_1.length;
      };
      Iterator_1.prototype.next_mz6i19_k$ = function() {
        var tmp;
        if (this.index_1 < this.array_1.length) {
          var tmp$ret$0;
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          var tmp0_toULong = this.array_1[tmp1];
          tmp$ret$0 = _ULong___init__impl__c78o9k(tmp0_toULong);
          tmp = tmp$ret$0;
        } else {
          throw NoSuchElementException_init_$Create$_0(this.index_1.toString());
        }
        return tmp;
      };
      Iterator_1.prototype.next_20eer_k$ = function() {
        return new ULong(this.next_mz6i19_k$());
      };
      Iterator_1.$metadata$ = classMeta("Iterator", [Iterator_3]);
      function ULongArray__contains_impl_v9bgai($this, element) {
        var tmp = isObject3(new ULong(element)) ? new ULong(element) : THROW_CCE();
        if (!(tmp instanceof ULong))
          return false;
        var tmp_0 = _ULongArray___get_storage__impl__28e64j($this);
        var tmp$ret$0;
        tmp$ret$0 = _ULong___get_data__impl__fggpzb(element);
        return contains_4(tmp_0, tmp$ret$0);
      }
      function ULongArray__contains_impl_v9bgai_0($this, element) {
        if (!(element instanceof ULong))
          return false;
        var tmp = $this.storage_1;
        return ULongArray__contains_impl_v9bgai(tmp, element instanceof ULong ? element.data_1 : THROW_CCE());
      }
      function ULongArray__containsAll_impl_xx8ztf($this, elements) {
        var tmp$ret$0;
        $l$block_0: {
          var tmp0_all = isInterface(elements, Collection) ? elements : THROW_CCE();
          var tmp;
          if (isInterface(tmp0_all, Collection)) {
            tmp = tmp0_all.isEmpty_y1axqb_k$();
          } else {
            tmp = false;
          }
          if (tmp) {
            tmp$ret$0 = true;
            break $l$block_0;
          }
          var tmp0_iterator = tmp0_all.iterator_jk1svi_k$();
          while (tmp0_iterator.hasNext_bitz1p_k$()) {
            var element = tmp0_iterator.next_20eer_k$();
            var tmp$ret$2;
            var tmp_0;
            if (element instanceof ULong) {
              var tmp_1 = _ULongArray___get_storage__impl__28e64j($this);
              var tmp$ret$1;
              var tmp0_toLong = element.data_1;
              tmp$ret$1 = _ULong___get_data__impl__fggpzb(tmp0_toLong);
              tmp_0 = contains_4(tmp_1, tmp$ret$1);
            } else {
              tmp_0 = false;
            }
            tmp$ret$2 = tmp_0;
            if (!tmp$ret$2) {
              tmp$ret$0 = false;
              break $l$block_0;
            }
          }
          tmp$ret$0 = true;
        }
        return tmp$ret$0;
      }
      function ULongArray__containsAll_impl_xx8ztf_0($this, elements) {
        return ULongArray__containsAll_impl_xx8ztf($this.storage_1, elements);
      }
      function ULongArray__isEmpty_impl_c3yngu($this) {
        return _ULongArray___get_storage__impl__28e64j($this).length === 0;
      }
      function ULongArray__toString_impl_wqk1p5($this) {
        return "ULongArray(storage=" + toString_1($this) + ")";
      }
      function ULongArray__hashCode_impl_aze4wa($this) {
        return hashCode($this);
      }
      function ULongArray__equals_impl_vwitwa($this, other) {
        if (!(other instanceof ULongArray))
          return false;
        var tmp0_other_with_cast = other instanceof ULongArray ? other.storage_1 : THROW_CCE();
        if (!equals($this, tmp0_other_with_cast))
          return false;
        return true;
      }
      function ULongArray(storage) {
        this.storage_1 = storage;
      }
      ULongArray.prototype.get_size_woubt6_k$ = function() {
        return _ULongArray___get_size__impl__ju6dtr(this.storage_1);
      };
      ULongArray.prototype.iterator_jk1svi_k$ = function() {
        return ULongArray__iterator_impl_cq4d2h(this.storage_1);
      };
      ULongArray.prototype.contains_6szeck_k$ = function(element) {
        return ULongArray__contains_impl_v9bgai(this.storage_1, element);
      };
      ULongArray.prototype.contains_2ehdt1_k$ = function(element) {
        return ULongArray__contains_impl_v9bgai_0(this, element);
      };
      ULongArray.prototype.containsAll_4csp1_k$ = function(elements) {
        return ULongArray__containsAll_impl_xx8ztf(this.storage_1, elements);
      };
      ULongArray.prototype.containsAll_jr3fla_k$ = function(elements) {
        return ULongArray__containsAll_impl_xx8ztf_0(this, elements);
      };
      ULongArray.prototype.isEmpty_y1axqb_k$ = function() {
        return ULongArray__isEmpty_impl_c3yngu(this.storage_1);
      };
      ULongArray.prototype.toString = function() {
        return ULongArray__toString_impl_wqk1p5(this.storage_1);
      };
      ULongArray.prototype.hashCode = function() {
        return ULongArray__hashCode_impl_aze4wa(this.storage_1);
      };
      ULongArray.prototype.equals = function(other) {
        return ULongArray__equals_impl_vwitwa(this.storage_1, other);
      };
      ULongArray.$metadata$ = classMeta("ULongArray", [Collection]);
      function Companion_15() {
        Companion_instance_15 = this;
        var tmp = this;
        Companion_getInstance_14();
        var tmp_0 = _ULong___init__impl__c78o9k(new Long(-1, -1));
        Companion_getInstance_14();
        tmp.EMPTY_1 = new ULongRange(tmp_0, _ULong___init__impl__c78o9k(new Long(0, 0)));
      }
      Companion_15.prototype.get_EMPTY_i8q41w_k$ = function() {
        return this.EMPTY_1;
      };
      Companion_15.$metadata$ = objectMeta("Companion");
      var Companion_instance_15;
      function Companion_getInstance_15() {
        if (Companion_instance_15 == null)
          new Companion_15();
        return Companion_instance_15;
      }
      function ULongRange(start2, endInclusive) {
        Companion_getInstance_15();
        ULongProgression.call(this, start2, endInclusive, new Long(1, 0));
      }
      ULongRange.prototype.get_start_tpgxg3_k$ = function() {
        return this.first_1;
      };
      ULongRange.prototype.get_start_iypx6h_k$ = function() {
        return new ULong(this.get_start_tpgxg3_k$());
      };
      ULongRange.prototype.get_endInclusive_gj8vho_k$ = function() {
        return this.last_1;
      };
      ULongRange.prototype.get_endInclusive_r07xpi_k$ = function() {
        return new ULong(this.get_endInclusive_gj8vho_k$());
      };
      ULongRange.prototype.get_endExclusive_q3rncq_k$ = function() {
        var tmp = new ULong(this.last_1);
        Companion_getInstance_14();
        if (equals(tmp, new ULong(_ULong___init__impl__c78o9k(new Long(-1, -1))))) {
          throw IllegalStateException_init_$Create$_0("Cannot return the exclusive upper bound of a range that includes MAX_VALUE.");
        }
        var tmp$ret$2;
        var tmp0_plus = this.last_1;
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UInt___get_data__impl__f0vqqw(_UInt___init__impl__l7qpdl(1))).and_jhajnj_k$(new Long(-1, 0)));
        var tmp0_plus_0 = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_plus).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(tmp0_plus_0)));
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      };
      ULongRange.prototype.get_endExclusive_pmwm6k_k$ = function() {
        return new ULong(this.get_endExclusive_q3rncq_k$());
      };
      ULongRange.prototype.contains_6szeck_k$ = function(value) {
        var tmp;
        var tmp$ret$0;
        var tmp0_compareTo = this.first_1;
        tmp$ret$0 = ulongCompare(_ULong___get_data__impl__fggpzb(tmp0_compareTo), _ULong___get_data__impl__fggpzb(value));
        if (tmp$ret$0 <= 0) {
          var tmp$ret$1;
          var tmp1_compareTo = this.last_1;
          tmp$ret$1 = ulongCompare(_ULong___get_data__impl__fggpzb(value), _ULong___get_data__impl__fggpzb(tmp1_compareTo));
          tmp = tmp$ret$1 <= 0;
        } else {
          tmp = false;
        }
        return tmp;
      };
      ULongRange.prototype.contains_2ehdtg_k$ = function(value) {
        return this.contains_6szeck_k$(value instanceof ULong ? value.data_1 : THROW_CCE());
      };
      ULongRange.prototype.isEmpty_y1axqb_k$ = function() {
        var tmp$ret$0;
        var tmp0_compareTo = this.first_1;
        var tmp1_compareTo = this.last_1;
        tmp$ret$0 = ulongCompare(_ULong___get_data__impl__fggpzb(tmp0_compareTo), _ULong___get_data__impl__fggpzb(tmp1_compareTo));
        return tmp$ret$0 > 0;
      };
      ULongRange.prototype.equals = function(other) {
        var tmp;
        if (other instanceof ULongRange) {
          tmp = (this.isEmpty_y1axqb_k$() ? other.isEmpty_y1axqb_k$() : false) ? true : equals(this.first_1, other.first_1) ? equals(this.last_1, other.last_1) : false;
        } else {
          tmp = false;
        }
        return tmp;
      };
      ULongRange.prototype.hashCode = function() {
        var tmp;
        if (this.isEmpty_y1axqb_k$()) {
          tmp = -1;
        } else {
          var tmp$ret$2;
          var tmp$ret$1;
          var tmp1_xor = this.first_1;
          var tmp$ret$0;
          var tmp0_shr = this.first_1;
          tmp$ret$0 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_shr).ushr_rr8rvr_k$(32));
          var tmp2_xor = tmp$ret$0;
          tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp1_xor).xor_jjua9n_k$(_ULong___get_data__impl__fggpzb(tmp2_xor)));
          var tmp3_toInt = tmp$ret$1;
          tmp$ret$2 = _ULong___get_data__impl__fggpzb(tmp3_toInt).toInt_1tsl84_k$();
          var tmp_0 = imul(31, tmp$ret$2);
          var tmp$ret$5;
          var tmp$ret$4;
          var tmp5_xor = this.last_1;
          var tmp$ret$3;
          var tmp4_shr = this.last_1;
          tmp$ret$3 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp4_shr).ushr_rr8rvr_k$(32));
          var tmp6_xor = tmp$ret$3;
          tmp$ret$4 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp5_xor).xor_jjua9n_k$(_ULong___get_data__impl__fggpzb(tmp6_xor)));
          var tmp7_toInt = tmp$ret$4;
          tmp$ret$5 = _ULong___get_data__impl__fggpzb(tmp7_toInt).toInt_1tsl84_k$();
          tmp = tmp_0 + tmp$ret$5 | 0;
        }
        return tmp;
      };
      ULongRange.prototype.toString = function() {
        return "" + new ULong(this.first_1) + ".." + new ULong(this.last_1);
      };
      ULongRange.$metadata$ = classMeta("ULongRange", [ClosedRange, OpenEndRange], void 0, void 0, void 0, ULongProgression.prototype);
      function Companion_16() {
        Companion_instance_16 = this;
      }
      Companion_16.prototype.fromClosedRange_wj18r3_k$ = function(rangeStart, rangeEnd, step) {
        return new ULongProgression(rangeStart, rangeEnd, step);
      };
      Companion_16.$metadata$ = objectMeta("Companion");
      var Companion_instance_16;
      function Companion_getInstance_16() {
        if (Companion_instance_16 == null)
          new Companion_16();
        return Companion_instance_16;
      }
      function ULongProgression(start2, endInclusive, step) {
        Companion_getInstance_16();
        if (step.equals(new Long(0, 0)))
          throw IllegalArgumentException_init_$Create$_0("Step must be non-zero.");
        Companion_getInstance_20();
        if (step.equals(new Long(0, -2147483648)))
          throw IllegalArgumentException_init_$Create$_0("Step must be greater than Long.MIN_VALUE to avoid overflow on negation.");
        this.first_1 = start2;
        this.last_1 = getProgressionLastElement_2(start2, endInclusive, step);
        this.step_1 = step;
      }
      ULongProgression.prototype.get_first_s0oavz_k$ = function() {
        return this.first_1;
      };
      ULongProgression.prototype.get_last_6gle4n_k$ = function() {
        return this.last_1;
      };
      ULongProgression.prototype.get_step_woujh1_k$ = function() {
        return this.step_1;
      };
      ULongProgression.prototype.iterator_jk1svi_k$ = function() {
        return new ULongProgressionIterator(this.first_1, this.last_1, this.step_1);
      };
      ULongProgression.prototype.isEmpty_y1axqb_k$ = function() {
        var tmp;
        if (this.step_1.compareTo_n4fqi2_k$(new Long(0, 0)) > 0) {
          var tmp$ret$0;
          var tmp0_compareTo = this.first_1;
          var tmp1_compareTo = this.last_1;
          tmp$ret$0 = ulongCompare(_ULong___get_data__impl__fggpzb(tmp0_compareTo), _ULong___get_data__impl__fggpzb(tmp1_compareTo));
          tmp = tmp$ret$0 > 0;
        } else {
          var tmp$ret$1;
          var tmp2_compareTo = this.first_1;
          var tmp3_compareTo = this.last_1;
          tmp$ret$1 = ulongCompare(_ULong___get_data__impl__fggpzb(tmp2_compareTo), _ULong___get_data__impl__fggpzb(tmp3_compareTo));
          tmp = tmp$ret$1 < 0;
        }
        return tmp;
      };
      ULongProgression.prototype.equals = function(other) {
        var tmp;
        if (other instanceof ULongProgression) {
          tmp = (this.isEmpty_y1axqb_k$() ? other.isEmpty_y1axqb_k$() : false) ? true : (equals(this.first_1, other.first_1) ? equals(this.last_1, other.last_1) : false) ? this.step_1.equals(other.step_1) : false;
        } else {
          tmp = false;
        }
        return tmp;
      };
      ULongProgression.prototype.hashCode = function() {
        var tmp;
        if (this.isEmpty_y1axqb_k$()) {
          tmp = -1;
        } else {
          var tmp$ret$2;
          var tmp$ret$1;
          var tmp1_xor = this.first_1;
          var tmp$ret$0;
          var tmp0_shr = this.first_1;
          tmp$ret$0 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_shr).ushr_rr8rvr_k$(32));
          var tmp2_xor = tmp$ret$0;
          tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp1_xor).xor_jjua9n_k$(_ULong___get_data__impl__fggpzb(tmp2_xor)));
          var tmp3_toInt = tmp$ret$1;
          tmp$ret$2 = _ULong___get_data__impl__fggpzb(tmp3_toInt).toInt_1tsl84_k$();
          var tmp_0 = imul(31, tmp$ret$2);
          var tmp$ret$5;
          var tmp$ret$4;
          var tmp5_xor = this.last_1;
          var tmp$ret$3;
          var tmp4_shr = this.last_1;
          tmp$ret$3 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp4_shr).ushr_rr8rvr_k$(32));
          var tmp6_xor = tmp$ret$3;
          tmp$ret$4 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp5_xor).xor_jjua9n_k$(_ULong___get_data__impl__fggpzb(tmp6_xor)));
          var tmp7_toInt = tmp$ret$4;
          tmp$ret$5 = _ULong___get_data__impl__fggpzb(tmp7_toInt).toInt_1tsl84_k$();
          tmp = imul(31, tmp_0 + tmp$ret$5 | 0) + this.step_1.xor_jjua9n_k$(this.step_1.ushr_rr8rvr_k$(32)).toInt_1tsl84_k$() | 0;
        }
        return tmp;
      };
      ULongProgression.prototype.toString = function() {
        return this.step_1.compareTo_n4fqi2_k$(new Long(0, 0)) > 0 ? "" + new ULong(this.first_1) + ".." + new ULong(this.last_1) + " step " + toString_1(this.step_1) : "" + new ULong(this.first_1) + " downTo " + new ULong(this.last_1) + " step " + toString_1(this.step_1.unaryMinus_6uz0qp_k$());
      };
      ULongProgression.$metadata$ = classMeta("ULongProgression", [Iterable]);
      function _get_finalElement__gc6m3p_3($this) {
        return $this.finalElement_1;
      }
      function _set_hasNext__86v2bs_3($this, _set____db54di) {
        $this.hasNext_1 = _set____db54di;
      }
      function _get_hasNext__xt3cos_3($this) {
        return $this.hasNext_1;
      }
      function _get_step__ddv2tb_0($this) {
        return $this.step_1;
      }
      function _set_next__9r2xms_3($this, _set____db54di) {
        $this.next_1 = _set____db54di;
      }
      function _get_next__daux88_3($this) {
        return $this.next_1;
      }
      function ULongProgressionIterator(first, last, step) {
        this.finalElement_1 = last;
        var tmp = this;
        var tmp_0;
        if (step.compareTo_n4fqi2_k$(new Long(0, 0)) > 0) {
          var tmp$ret$0;
          tmp$ret$0 = ulongCompare(_ULong___get_data__impl__fggpzb(first), _ULong___get_data__impl__fggpzb(last));
          tmp_0 = tmp$ret$0 <= 0;
        } else {
          var tmp$ret$1;
          tmp$ret$1 = ulongCompare(_ULong___get_data__impl__fggpzb(first), _ULong___get_data__impl__fggpzb(last));
          tmp_0 = tmp$ret$1 >= 0;
        }
        tmp.hasNext_1 = tmp_0;
        var tmp_1 = this;
        var tmp$ret$2;
        tmp$ret$2 = _ULong___init__impl__c78o9k(step);
        tmp_1.step_1 = tmp$ret$2;
        this.next_1 = this.hasNext_1 ? first : this.finalElement_1;
      }
      ULongProgressionIterator.prototype.hasNext_bitz1p_k$ = function() {
        return this.hasNext_1;
      };
      ULongProgressionIterator.prototype.next_mz6i19_k$ = function() {
        var value = this.next_1;
        if (equals(value, this.finalElement_1)) {
          if (!this.hasNext_1)
            throw NoSuchElementException_init_$Create$();
          this.hasNext_1 = false;
        } else {
          var tmp0_this = this;
          var tmp = tmp0_this;
          var tmp$ret$0;
          var tmp0_plus = tmp0_this.next_1;
          var tmp1_plus = this.step_1;
          tmp$ret$0 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_plus).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(tmp1_plus)));
          tmp.next_1 = tmp$ret$0;
        }
        return value;
      };
      ULongProgressionIterator.prototype.next_20eer_k$ = function() {
        return new ULong(this.next_mz6i19_k$());
      };
      ULongProgressionIterator.$metadata$ = classMeta("ULongProgressionIterator", [Iterator_3]);
      function getProgressionLastElement_1(start2, end, step) {
        var tmp;
        if (step > 0) {
          var tmp_0;
          var tmp$ret$0;
          tmp$ret$0 = uintCompare(_UInt___get_data__impl__f0vqqw(start2), _UInt___get_data__impl__f0vqqw(end));
          if (tmp$ret$0 >= 0) {
            tmp_0 = end;
          } else {
            var tmp$ret$2;
            var tmp$ret$1;
            tmp$ret$1 = _UInt___init__impl__l7qpdl(step);
            var tmp0_minus = differenceModulo_1(end, start2, tmp$ret$1);
            tmp$ret$2 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(end) - _UInt___get_data__impl__f0vqqw(tmp0_minus) | 0);
            tmp_0 = tmp$ret$2;
          }
          tmp = tmp_0;
        } else if (step < 0) {
          var tmp_1;
          var tmp$ret$3;
          tmp$ret$3 = uintCompare(_UInt___get_data__impl__f0vqqw(start2), _UInt___get_data__impl__f0vqqw(end));
          if (tmp$ret$3 <= 0) {
            tmp_1 = end;
          } else {
            var tmp$ret$5;
            var tmp$ret$4;
            var tmp1_toUInt = -step | 0;
            tmp$ret$4 = _UInt___init__impl__l7qpdl(tmp1_toUInt);
            var tmp2_plus = differenceModulo_1(start2, end, tmp$ret$4);
            tmp$ret$5 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(end) + _UInt___get_data__impl__f0vqqw(tmp2_plus) | 0);
            tmp_1 = tmp$ret$5;
          }
          tmp = tmp_1;
        } else {
          throw IllegalArgumentException_init_$Create$_0("Step is zero.");
        }
        return tmp;
      }
      function getProgressionLastElement_2(start2, end, step) {
        var tmp;
        if (step.compareTo_n4fqi2_k$(new Long(0, 0)) > 0) {
          var tmp_0;
          var tmp$ret$0;
          tmp$ret$0 = ulongCompare(_ULong___get_data__impl__fggpzb(start2), _ULong___get_data__impl__fggpzb(end));
          if (tmp$ret$0 >= 0) {
            tmp_0 = end;
          } else {
            var tmp$ret$2;
            var tmp$ret$1;
            tmp$ret$1 = _ULong___init__impl__c78o9k(step);
            var tmp0_minus = differenceModulo_2(end, start2, tmp$ret$1);
            tmp$ret$2 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(end).minus_llf5ei_k$(_ULong___get_data__impl__fggpzb(tmp0_minus)));
            tmp_0 = tmp$ret$2;
          }
          tmp = tmp_0;
        } else if (step.compareTo_n4fqi2_k$(new Long(0, 0)) < 0) {
          var tmp_1;
          var tmp$ret$3;
          tmp$ret$3 = ulongCompare(_ULong___get_data__impl__fggpzb(start2), _ULong___get_data__impl__fggpzb(end));
          if (tmp$ret$3 <= 0) {
            tmp_1 = end;
          } else {
            var tmp$ret$5;
            var tmp$ret$4;
            var tmp1_toULong = step.unaryMinus_6uz0qp_k$();
            tmp$ret$4 = _ULong___init__impl__c78o9k(tmp1_toULong);
            var tmp2_plus = differenceModulo_2(start2, end, tmp$ret$4);
            tmp$ret$5 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(end).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(tmp2_plus)));
            tmp_1 = tmp$ret$5;
          }
          tmp = tmp_1;
        } else {
          throw IllegalArgumentException_init_$Create$_0("Step is zero.");
        }
        return tmp;
      }
      function differenceModulo_1(a, b, c) {
        var tmp$ret$0;
        tmp$ret$0 = uintRemainder(a, c);
        var ac = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = uintRemainder(b, c);
        var bc = tmp$ret$1;
        var tmp;
        var tmp$ret$2;
        tmp$ret$2 = uintCompare(_UInt___get_data__impl__f0vqqw(ac), _UInt___get_data__impl__f0vqqw(bc));
        if (tmp$ret$2 >= 0) {
          var tmp$ret$3;
          tmp$ret$3 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(ac) - _UInt___get_data__impl__f0vqqw(bc) | 0);
          tmp = tmp$ret$3;
        } else {
          var tmp$ret$5;
          var tmp$ret$4;
          tmp$ret$4 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(ac) - _UInt___get_data__impl__f0vqqw(bc) | 0);
          var tmp0_plus = tmp$ret$4;
          tmp$ret$5 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_plus) + _UInt___get_data__impl__f0vqqw(c) | 0);
          tmp = tmp$ret$5;
        }
        return tmp;
      }
      function differenceModulo_2(a, b, c) {
        var tmp$ret$0;
        tmp$ret$0 = ulongRemainder(a, c);
        var ac = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongRemainder(b, c);
        var bc = tmp$ret$1;
        var tmp;
        var tmp$ret$2;
        tmp$ret$2 = ulongCompare(_ULong___get_data__impl__fggpzb(ac), _ULong___get_data__impl__fggpzb(bc));
        if (tmp$ret$2 >= 0) {
          var tmp$ret$3;
          tmp$ret$3 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(ac).minus_llf5ei_k$(_ULong___get_data__impl__fggpzb(bc)));
          tmp = tmp$ret$3;
        } else {
          var tmp$ret$5;
          var tmp$ret$4;
          tmp$ret$4 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(ac).minus_llf5ei_k$(_ULong___get_data__impl__fggpzb(bc)));
          var tmp0_plus = tmp$ret$4;
          tmp$ret$5 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_plus).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(c)));
          tmp = tmp$ret$5;
        }
        return tmp;
      }
      function _UShort___init__impl__jigrne(data) {
        return data;
      }
      function _UShort___get_data__impl__g0245($this) {
        return $this;
      }
      function Companion_17() {
        Companion_instance_17 = this;
        this.MIN_VALUE_1 = _UShort___init__impl__jigrne(0);
        this.MAX_VALUE_1 = _UShort___init__impl__jigrne(-1);
        this.SIZE_BYTES_1 = 2;
        this.SIZE_BITS_1 = 16;
      }
      Companion_17.prototype.get_MIN_VALUE_5rgn3n_k$ = function() {
        return this.MIN_VALUE_1;
      };
      Companion_17.prototype.get_MAX_VALUE_1r6om7_k$ = function() {
        return this.MAX_VALUE_1;
      };
      Companion_17.prototype.get_SIZE_BYTES_qphg4q_k$ = function() {
        return this.SIZE_BYTES_1;
      };
      Companion_17.prototype.get_SIZE_BITS_7qhjj9_k$ = function() {
        return this.SIZE_BITS_1;
      };
      Companion_17.$metadata$ = objectMeta("Companion");
      var Companion_instance_17;
      function Companion_getInstance_17() {
        if (Companion_instance_17 == null)
          new Companion_17();
        return Companion_instance_17;
      }
      function UShort__compareTo_impl_1pfgyc($this, other) {
        var tmp$ret$0;
        tmp$ret$0 = _UShort___get_data__impl__g0245($this) & 65535;
        var tmp = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UByte___get_data__impl__jof9qr(other) & 255;
        return compareTo_0(tmp, tmp$ret$1);
      }
      function UShort__compareTo_impl_1pfgyc_0($this, other) {
        var tmp$ret$0;
        tmp$ret$0 = _UShort___get_data__impl__g0245($this) & 65535;
        var tmp = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UShort___get_data__impl__g0245(other) & 65535;
        return compareTo_0(tmp, tmp$ret$1);
      }
      function UShort__compareTo_impl_1pfgyc_1($this, other) {
        var tmp = $this.data_1;
        return UShort__compareTo_impl_1pfgyc_0(tmp, other instanceof UShort ? other.data_1 : THROW_CCE());
      }
      function UShort__compareTo_impl_1pfgyc_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_compareTo = tmp$ret$0;
        tmp$ret$1 = uintCompare(_UInt___get_data__impl__f0vqqw(tmp0_compareTo), _UInt___get_data__impl__f0vqqw(other));
        return tmp$ret$1;
      }
      function UShort__compareTo_impl_1pfgyc_3($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245($this)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_compareTo = tmp$ret$0;
        tmp$ret$1 = ulongCompare(_ULong___get_data__impl__fggpzb(tmp0_compareTo), _ULong___get_data__impl__fggpzb(other));
        return tmp$ret$1;
      }
      function UShort__plus_impl_s0k2d0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_plus = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_plus = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_plus) + _UInt___get_data__impl__f0vqqw(tmp1_plus) | 0);
        return tmp$ret$2;
      }
      function UShort__plus_impl_s0k2d0_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_plus = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_plus = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_plus) + _UInt___get_data__impl__f0vqqw(tmp1_plus) | 0);
        return tmp$ret$2;
      }
      function UShort__plus_impl_s0k2d0_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_plus = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_plus) + _UInt___get_data__impl__f0vqqw(other) | 0);
        return tmp$ret$1;
      }
      function UShort__plus_impl_s0k2d0_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245($this)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_plus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_plus).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(other)));
        return tmp$ret$1;
      }
      function UShort__minus_impl_e61690($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_minus = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_minus = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_minus) - _UInt___get_data__impl__f0vqqw(tmp1_minus) | 0);
        return tmp$ret$2;
      }
      function UShort__minus_impl_e61690_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_minus = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_minus = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_minus) - _UInt___get_data__impl__f0vqqw(tmp1_minus) | 0);
        return tmp$ret$2;
      }
      function UShort__minus_impl_e61690_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_minus = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp0_minus) - _UInt___get_data__impl__f0vqqw(other) | 0);
        return tmp$ret$1;
      }
      function UShort__minus_impl_e61690_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245($this)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_minus = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_minus).minus_llf5ei_k$(_ULong___get_data__impl__fggpzb(other)));
        return tmp$ret$1;
      }
      function UShort__times_impl_bvilzi($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_times = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_times = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(imul(_UInt___get_data__impl__f0vqqw(tmp0_times), _UInt___get_data__impl__f0vqqw(tmp1_times)));
        return tmp$ret$2;
      }
      function UShort__times_impl_bvilzi_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_times = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_times = tmp$ret$1;
        tmp$ret$2 = _UInt___init__impl__l7qpdl(imul(_UInt___get_data__impl__f0vqqw(tmp0_times), _UInt___get_data__impl__f0vqqw(tmp1_times)));
        return tmp$ret$2;
      }
      function UShort__times_impl_bvilzi_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_times = tmp$ret$0;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(imul(_UInt___get_data__impl__f0vqqw(tmp0_times), _UInt___get_data__impl__f0vqqw(other)));
        return tmp$ret$1;
      }
      function UShort__times_impl_bvilzi_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245($this)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_times = tmp$ret$0;
        tmp$ret$1 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp0_times).times_2zfqpc_k$(_ULong___get_data__impl__fggpzb(other)));
        return tmp$ret$1;
      }
      function UShort__div_impl_b0o0rh($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_div = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_div = tmp$ret$1;
        tmp$ret$2 = uintDivide(tmp0_div, tmp1_div);
        return tmp$ret$2;
      }
      function UShort__div_impl_b0o0rh_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_div = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_div = tmp$ret$1;
        tmp$ret$2 = uintDivide(tmp0_div, tmp1_div);
        return tmp$ret$2;
      }
      function UShort__div_impl_b0o0rh_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_div = tmp$ret$0;
        tmp$ret$1 = uintDivide(tmp0_div, other);
        return tmp$ret$1;
      }
      function UShort__div_impl_b0o0rh_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245($this)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_div = tmp$ret$0;
        tmp$ret$1 = ulongDivide(tmp0_div, other);
        return tmp$ret$1;
      }
      function UShort__rem_impl_pmhe86($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_rem = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_rem = tmp$ret$1;
        tmp$ret$2 = uintRemainder(tmp0_rem, tmp1_rem);
        return tmp$ret$2;
      }
      function UShort__rem_impl_pmhe86_0($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_rem = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_rem = tmp$ret$1;
        tmp$ret$2 = uintRemainder(tmp0_rem, tmp1_rem);
        return tmp$ret$2;
      }
      function UShort__rem_impl_pmhe86_1($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_rem = tmp$ret$0;
        tmp$ret$1 = uintRemainder(tmp0_rem, other);
        return tmp$ret$1;
      }
      function UShort__rem_impl_pmhe86_2($this, other) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245($this)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_rem = tmp$ret$0;
        tmp$ret$1 = ulongRemainder(tmp0_rem, other);
        return tmp$ret$1;
      }
      function UShort__floorDiv_impl_gebnkx($this, other) {
        var tmp$ret$3;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_floorDiv = tmp$ret$1;
        var tmp$ret$2;
        tmp$ret$2 = uintDivide(tmp0_floorDiv, tmp1_floorDiv);
        tmp$ret$3 = tmp$ret$2;
        return tmp$ret$3;
      }
      function UShort__floorDiv_impl_gebnkx_0($this, other) {
        var tmp$ret$3;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_floorDiv = tmp$ret$1;
        var tmp$ret$2;
        tmp$ret$2 = uintDivide(tmp0_floorDiv, tmp1_floorDiv);
        tmp$ret$3 = tmp$ret$2;
        return tmp$ret$3;
      }
      function UShort__floorDiv_impl_gebnkx_1($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = uintDivide(tmp0_floorDiv, other);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UShort__floorDiv_impl_gebnkx_2($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245($this)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_floorDiv = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongDivide(tmp0_floorDiv, other);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UShort__mod_impl_r81ium($this, other) {
        var tmp$ret$5;
        var tmp$ret$3;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UByte___get_data__impl__jof9qr(other) & 255);
        var tmp1_mod = tmp$ret$1;
        var tmp$ret$2;
        tmp$ret$2 = uintRemainder(tmp0_mod, tmp1_mod);
        tmp$ret$3 = tmp$ret$2;
        var tmp2_toUByte = tmp$ret$3;
        var tmp$ret$4;
        var tmp0_toUByte = _UInt___get_data__impl__f0vqqw(tmp2_toUByte);
        tmp$ret$4 = _UByte___init__impl__g9hnc4(toByte(tmp0_toUByte));
        tmp$ret$5 = tmp$ret$4;
        return tmp$ret$5;
      }
      function UShort__mod_impl_r81ium_0($this, other) {
        var tmp$ret$5;
        var tmp$ret$3;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        var tmp1_mod = tmp$ret$1;
        var tmp$ret$2;
        tmp$ret$2 = uintRemainder(tmp0_mod, tmp1_mod);
        tmp$ret$3 = tmp$ret$2;
        var tmp2_toUShort = tmp$ret$3;
        var tmp$ret$4;
        var tmp0_toUShort = _UInt___get_data__impl__f0vqqw(tmp2_toUShort);
        tmp$ret$4 = _UShort___init__impl__jigrne(toShort(tmp0_toUShort));
        tmp$ret$5 = tmp$ret$4;
        return tmp$ret$5;
      }
      function UShort__mod_impl_r81ium_1($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = uintRemainder(tmp0_mod, other);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UShort__mod_impl_r81ium_2($this, other) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245($this)).and_jhajnj_k$(new Long(65535, 0)));
        var tmp0_mod = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = ulongRemainder(tmp0_mod, other);
        tmp$ret$2 = tmp$ret$1;
        return tmp$ret$2;
      }
      function UShort__inc_impl_flr7re($this) {
        return _UShort___init__impl__jigrne(numberToShort(_UShort___get_data__impl__g0245($this) + 1));
      }
      function UShort__dec_impl_7ozx66($this) {
        return _UShort___init__impl__jigrne(numberToShort(_UShort___get_data__impl__g0245($this) - 1));
      }
      function UShort__rangeTo_impl_xfunss($this, other) {
        var tmp$ret$0;
        tmp$ret$0 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
        var tmp = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245(other) & 65535);
        return new UIntRange(tmp, tmp$ret$1);
      }
      function UShort__and_impl_wmd7xf($this, other) {
        var tmp$ret$0;
        var tmp0_and = _UShort___get_data__impl__g0245($this);
        var tmp1_and = _UShort___get_data__impl__g0245(other);
        tmp$ret$0 = toShort(tmp0_and & tmp1_and);
        return _UShort___init__impl__jigrne(tmp$ret$0);
      }
      function UShort__or_impl_uhj9st($this, other) {
        var tmp$ret$0;
        var tmp0_or = _UShort___get_data__impl__g0245($this);
        var tmp1_or = _UShort___get_data__impl__g0245(other);
        tmp$ret$0 = toShort(tmp0_or | tmp1_or);
        return _UShort___init__impl__jigrne(tmp$ret$0);
      }
      function UShort__xor_impl_cc06ft($this, other) {
        var tmp$ret$0;
        var tmp0_xor = _UShort___get_data__impl__g0245($this);
        var tmp1_xor = _UShort___get_data__impl__g0245(other);
        tmp$ret$0 = toShort(tmp0_xor ^ tmp1_xor);
        return _UShort___init__impl__jigrne(tmp$ret$0);
      }
      function UShort__inv_impl_6lwe9p($this) {
        var tmp$ret$0;
        var tmp0_inv = _UShort___get_data__impl__g0245($this);
        tmp$ret$0 = toShort(~tmp0_inv);
        return _UShort___init__impl__jigrne(tmp$ret$0);
      }
      function UShort__toByte_impl_m9fcil($this) {
        return toByte(_UShort___get_data__impl__g0245($this));
      }
      function UShort__toShort_impl_fqwi31($this) {
        return _UShort___get_data__impl__g0245($this);
      }
      function UShort__toInt_impl_72bkww($this) {
        return _UShort___get_data__impl__g0245($this) & 65535;
      }
      function UShort__toLong_impl_ds1s6n($this) {
        return toLong(_UShort___get_data__impl__g0245($this)).and_jhajnj_k$(new Long(65535, 0));
      }
      function UShort__toUByte_impl_3ig9yq($this) {
        var tmp$ret$0;
        var tmp0_toUByte = _UShort___get_data__impl__g0245($this);
        tmp$ret$0 = _UByte___init__impl__g9hnc4(toByte(tmp0_toUByte));
        return tmp$ret$0;
      }
      function UShort__toUShort_impl_1x3938($this) {
        return $this;
      }
      function UShort__toUInt_impl_581pf5($this) {
        return _UInt___init__impl__l7qpdl(_UShort___get_data__impl__g0245($this) & 65535);
      }
      function UShort__toULong_impl_vh6nb6($this) {
        return _ULong___init__impl__c78o9k(toLong(_UShort___get_data__impl__g0245($this)).and_jhajnj_k$(new Long(65535, 0)));
      }
      function UShort__toFloat_impl_ckgf4j($this) {
        var tmp$ret$0;
        tmp$ret$0 = _UShort___get_data__impl__g0245($this) & 65535;
        return tmp$ret$0;
      }
      function UShort__toDouble_impl_g58lae($this) {
        var tmp$ret$0;
        tmp$ret$0 = _UShort___get_data__impl__g0245($this) & 65535;
        return tmp$ret$0;
      }
      function UShort__toString_impl_edaoee($this) {
        var tmp$ret$0;
        tmp$ret$0 = _UShort___get_data__impl__g0245($this) & 65535;
        return tmp$ret$0.toString();
      }
      function UShort__hashCode_impl_ywngrv($this) {
        return $this;
      }
      function UShort__equals_impl_7t9pdz($this, other) {
        if (!(other instanceof UShort))
          return false;
        var tmp0_other_with_cast = other instanceof UShort ? other.data_1 : THROW_CCE();
        if (!($this === tmp0_other_with_cast))
          return false;
        return true;
      }
      function UShort(data) {
        Companion_getInstance_17();
        this.data_1 = data;
      }
      UShort.prototype.compareTo_7e9yiz_k$ = function(other) {
        return UShort__compareTo_impl_1pfgyc_0(this.data_1, other);
      };
      UShort.prototype.compareTo_6thzaj_k$ = function(other) {
        return UShort__compareTo_impl_1pfgyc_1(this, other);
      };
      UShort.prototype.toString = function() {
        return UShort__toString_impl_edaoee(this.data_1);
      };
      UShort.prototype.hashCode = function() {
        return UShort__hashCode_impl_ywngrv(this.data_1);
      };
      UShort.prototype.equals = function(other) {
        return UShort__equals_impl_7t9pdz(this.data_1, other);
      };
      UShort.$metadata$ = classMeta("UShort", [Comparable]);
      function toUShort(_this__u8e3s4) {
        return _UShort___init__impl__jigrne(toShort(_this__u8e3s4));
      }
      function toUShort_0(_this__u8e3s4) {
        return _UShort___init__impl__jigrne(_this__u8e3s4.toShort_ja8oqn_k$());
      }
      function toUShort_1(_this__u8e3s4) {
        return _UShort___init__impl__jigrne(_this__u8e3s4);
      }
      function _get_array__jslnqg_2($this) {
        return $this.array_1;
      }
      function _set_index__fyfqnn_2($this, _set____db54di) {
        $this.index_1 = _set____db54di;
      }
      function _get_index__g2optt_2($this) {
        return $this.index_1;
      }
      function _UShortArray___init__impl__9b26ef(storage) {
        return storage;
      }
      function _UShortArray___get_storage__impl__t2jpv5($this) {
        return $this;
      }
      function _UShortArray___init__impl__9b26ef_0(size2) {
        var tmp = _UShortArray___init__impl__9b26ef(new Int16Array(size2));
        return tmp;
      }
      function UShortArray__get_impl_fnbhmx($this, index) {
        var tmp$ret$0;
        var tmp0_toUShort = _UShortArray___get_storage__impl__t2jpv5($this)[index];
        tmp$ret$0 = _UShort___init__impl__jigrne(tmp0_toUShort);
        return tmp$ret$0;
      }
      function UShortArray__set_impl_6d8whp($this, index, value) {
        var tmp = _UShortArray___get_storage__impl__t2jpv5($this);
        var tmp$ret$0;
        tmp$ret$0 = _UShort___get_data__impl__g0245(value);
        tmp[index] = tmp$ret$0;
      }
      function _UShortArray___get_size__impl__jqto1b($this) {
        return _UShortArray___get_storage__impl__t2jpv5($this).length;
      }
      function UShortArray__iterator_impl_ktpenn($this) {
        return new Iterator_2(_UShortArray___get_storage__impl__t2jpv5($this));
      }
      function Iterator_2(array3) {
        this.array_1 = array3;
        this.index_1 = 0;
      }
      Iterator_2.prototype.hasNext_bitz1p_k$ = function() {
        return this.index_1 < this.array_1.length;
      };
      Iterator_2.prototype.next_1vquzf_k$ = function() {
        var tmp;
        if (this.index_1 < this.array_1.length) {
          var tmp$ret$0;
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          var tmp0_toUShort = this.array_1[tmp1];
          tmp$ret$0 = _UShort___init__impl__jigrne(tmp0_toUShort);
          tmp = tmp$ret$0;
        } else {
          throw NoSuchElementException_init_$Create$_0(this.index_1.toString());
        }
        return tmp;
      };
      Iterator_2.prototype.next_20eer_k$ = function() {
        return new UShort(this.next_1vquzf_k$());
      };
      Iterator_2.$metadata$ = classMeta("Iterator", [Iterator_3]);
      function UShortArray__contains_impl_vo7k3g($this, element) {
        var tmp = isObject3(new UShort(element)) ? new UShort(element) : THROW_CCE();
        if (!(tmp instanceof UShort))
          return false;
        var tmp_0 = _UShortArray___get_storage__impl__t2jpv5($this);
        var tmp$ret$0;
        tmp$ret$0 = _UShort___get_data__impl__g0245(element);
        return contains_2(tmp_0, tmp$ret$0);
      }
      function UShortArray__contains_impl_vo7k3g_0($this, element) {
        if (!(element instanceof UShort))
          return false;
        var tmp = $this.storage_1;
        return UShortArray__contains_impl_vo7k3g(tmp, element instanceof UShort ? element.data_1 : THROW_CCE());
      }
      function UShortArray__containsAll_impl_vlaaxp($this, elements) {
        var tmp$ret$0;
        $l$block_0: {
          var tmp0_all = isInterface(elements, Collection) ? elements : THROW_CCE();
          var tmp;
          if (isInterface(tmp0_all, Collection)) {
            tmp = tmp0_all.isEmpty_y1axqb_k$();
          } else {
            tmp = false;
          }
          if (tmp) {
            tmp$ret$0 = true;
            break $l$block_0;
          }
          var tmp0_iterator = tmp0_all.iterator_jk1svi_k$();
          while (tmp0_iterator.hasNext_bitz1p_k$()) {
            var element = tmp0_iterator.next_20eer_k$();
            var tmp$ret$2;
            var tmp_0;
            if (element instanceof UShort) {
              var tmp_1 = _UShortArray___get_storage__impl__t2jpv5($this);
              var tmp$ret$1;
              var tmp0_toShort = element.data_1;
              tmp$ret$1 = _UShort___get_data__impl__g0245(tmp0_toShort);
              tmp_0 = contains_2(tmp_1, tmp$ret$1);
            } else {
              tmp_0 = false;
            }
            tmp$ret$2 = tmp_0;
            if (!tmp$ret$2) {
              tmp$ret$0 = false;
              break $l$block_0;
            }
          }
          tmp$ret$0 = true;
        }
        return tmp$ret$0;
      }
      function UShortArray__containsAll_impl_vlaaxp_0($this, elements) {
        return UShortArray__containsAll_impl_vlaaxp($this.storage_1, elements);
      }
      function UShortArray__isEmpty_impl_cdd9l0($this) {
        return _UShortArray___get_storage__impl__t2jpv5($this).length === 0;
      }
      function UShortArray__toString_impl_omz03z($this) {
        return "UShortArray(storage=" + toString_1($this) + ")";
      }
      function UShortArray__hashCode_impl_2vt3b4($this) {
        return hashCode($this);
      }
      function UShortArray__equals_impl_tyc3mk($this, other) {
        if (!(other instanceof UShortArray))
          return false;
        var tmp0_other_with_cast = other instanceof UShortArray ? other.storage_1 : THROW_CCE();
        if (!equals($this, tmp0_other_with_cast))
          return false;
        return true;
      }
      function UShortArray(storage) {
        this.storage_1 = storage;
      }
      UShortArray.prototype.get_size_woubt6_k$ = function() {
        return _UShortArray___get_size__impl__jqto1b(this.storage_1);
      };
      UShortArray.prototype.iterator_jk1svi_k$ = function() {
        return UShortArray__iterator_impl_ktpenn(this.storage_1);
      };
      UShortArray.prototype.contains_214orw_k$ = function(element) {
        return UShortArray__contains_impl_vo7k3g(this.storage_1, element);
      };
      UShortArray.prototype.contains_2ehdt1_k$ = function(element) {
        return UShortArray__contains_impl_vo7k3g_0(this, element);
      };
      UShortArray.prototype.containsAll_6yien3_k$ = function(elements) {
        return UShortArray__containsAll_impl_vlaaxp(this.storage_1, elements);
      };
      UShortArray.prototype.containsAll_jr3fla_k$ = function(elements) {
        return UShortArray__containsAll_impl_vlaaxp_0(this, elements);
      };
      UShortArray.prototype.isEmpty_y1axqb_k$ = function() {
        return UShortArray__isEmpty_impl_cdd9l0(this.storage_1);
      };
      UShortArray.prototype.toString = function() {
        return UShortArray__toString_impl_omz03z(this.storage_1);
      };
      UShortArray.prototype.hashCode = function() {
        return UShortArray__hashCode_impl_2vt3b4(this.storage_1);
      };
      UShortArray.prototype.equals = function(other) {
        return UShortArray__equals_impl_tyc3mk(this.storage_1, other);
      };
      UShortArray.$metadata$ = classMeta("UShortArray", [Collection]);
      function uintCompare(v1, v2) {
        return compareTo_0(v1 ^ IntCompanionObject_getInstance().MIN_VALUE_1, v2 ^ IntCompanionObject_getInstance().MIN_VALUE_1);
      }
      function uintDivide(v1, v2) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = toLong(_UInt___get_data__impl__f0vqqw(v1)).and_jhajnj_k$(new Long(-1, 0));
        var tmp = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = toLong(_UInt___get_data__impl__f0vqqw(v2)).and_jhajnj_k$(new Long(-1, 0));
        var tmp0_toUInt = tmp.div_9s1fi3_k$(tmp$ret$1);
        tmp$ret$2 = _UInt___init__impl__l7qpdl(tmp0_toUInt.toInt_1tsl84_k$());
        return tmp$ret$2;
      }
      function uintRemainder(v1, v2) {
        var tmp$ret$2;
        var tmp$ret$0;
        tmp$ret$0 = toLong(_UInt___get_data__impl__f0vqqw(v1)).and_jhajnj_k$(new Long(-1, 0));
        var tmp = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = toLong(_UInt___get_data__impl__f0vqqw(v2)).and_jhajnj_k$(new Long(-1, 0));
        var tmp0_toUInt = tmp.rem_9rbcjo_k$(tmp$ret$1);
        tmp$ret$2 = _UInt___init__impl__l7qpdl(tmp0_toUInt.toInt_1tsl84_k$());
        return tmp$ret$2;
      }
      function uintToDouble(v) {
        return (v & IntCompanionObject_getInstance().MAX_VALUE_1) + ((v >>> 31 | 0) << 30) * 2;
      }
      function ulongCompare(v1, v2) {
        Companion_getInstance_20();
        var tmp = v1.xor_jjua9n_k$(new Long(0, -2147483648));
        Companion_getInstance_20();
        return tmp.compareTo_n4fqi2_k$(v2.xor_jjua9n_k$(new Long(0, -2147483648)));
      }
      function ulongDivide(v1, v2) {
        var tmp$ret$0;
        tmp$ret$0 = _ULong___get_data__impl__fggpzb(v1);
        var dividend = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _ULong___get_data__impl__fggpzb(v2);
        var divisor = tmp$ret$1;
        if (divisor.compareTo_n4fqi2_k$(new Long(0, 0)) < 0) {
          var tmp;
          var tmp$ret$2;
          tmp$ret$2 = ulongCompare(_ULong___get_data__impl__fggpzb(v1), _ULong___get_data__impl__fggpzb(v2));
          if (tmp$ret$2 < 0) {
            tmp = _ULong___init__impl__c78o9k(new Long(0, 0));
          } else {
            tmp = _ULong___init__impl__c78o9k(new Long(1, 0));
          }
          return tmp;
        }
        if (dividend.compareTo_n4fqi2_k$(new Long(0, 0)) >= 0) {
          return _ULong___init__impl__c78o9k(dividend.div_9s1fi3_k$(divisor));
        }
        var quotient = dividend.ushr_rr8rvr_k$(1).div_9s1fi3_k$(divisor).shl_po5ip6_k$(1);
        var rem = dividend.minus_llf5ei_k$(quotient.times_2zfqpc_k$(divisor));
        var tmp$ret$4;
        var tmp_0;
        var tmp$ret$3;
        var tmp0_compareTo = _ULong___init__impl__c78o9k(rem);
        var tmp1_compareTo = _ULong___init__impl__c78o9k(divisor);
        tmp$ret$3 = ulongCompare(_ULong___get_data__impl__fggpzb(tmp0_compareTo), _ULong___get_data__impl__fggpzb(tmp1_compareTo));
        if (tmp$ret$3 >= 0) {
          tmp_0 = 1;
        } else {
          tmp_0 = 0;
        }
        var tmp2_plus = tmp_0;
        tmp$ret$4 = quotient.plus_u6jwas_k$(toLong(tmp2_plus));
        return _ULong___init__impl__c78o9k(tmp$ret$4);
      }
      function ulongRemainder(v1, v2) {
        var tmp$ret$0;
        tmp$ret$0 = _ULong___get_data__impl__fggpzb(v1);
        var dividend = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = _ULong___get_data__impl__fggpzb(v2);
        var divisor = tmp$ret$1;
        if (divisor.compareTo_n4fqi2_k$(new Long(0, 0)) < 0) {
          var tmp;
          var tmp$ret$2;
          tmp$ret$2 = ulongCompare(_ULong___get_data__impl__fggpzb(v1), _ULong___get_data__impl__fggpzb(v2));
          if (tmp$ret$2 < 0) {
            tmp = v1;
          } else {
            var tmp$ret$3;
            tmp$ret$3 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(v1).minus_llf5ei_k$(_ULong___get_data__impl__fggpzb(v2)));
            tmp = tmp$ret$3;
          }
          return tmp;
        }
        if (dividend.compareTo_n4fqi2_k$(new Long(0, 0)) >= 0) {
          return _ULong___init__impl__c78o9k(dividend.rem_9rbcjo_k$(divisor));
        }
        var quotient = dividend.ushr_rr8rvr_k$(1).div_9s1fi3_k$(divisor).shl_po5ip6_k$(1);
        var rem = dividend.minus_llf5ei_k$(quotient.times_2zfqpc_k$(divisor));
        var tmp_0;
        var tmp$ret$4;
        var tmp0_compareTo = _ULong___init__impl__c78o9k(rem);
        var tmp1_compareTo = _ULong___init__impl__c78o9k(divisor);
        tmp$ret$4 = ulongCompare(_ULong___get_data__impl__fggpzb(tmp0_compareTo), _ULong___get_data__impl__fggpzb(tmp1_compareTo));
        if (tmp$ret$4 >= 0) {
          tmp_0 = divisor;
        } else {
          tmp_0 = new Long(0, 0);
        }
        return _ULong___init__impl__c78o9k(rem.minus_llf5ei_k$(tmp_0));
      }
      function ulongToDouble(v) {
        return v.ushr_rr8rvr_k$(11).toDouble_ygsx0s_k$() * 2048 + v.and_jhajnj_k$(new Long(2047, 0)).toDouble_ygsx0s_k$();
      }
      function ulongToString(v) {
        return ulongToString_0(v, 10);
      }
      function ulongToString_0(v, base) {
        if (v.compareTo_n4fqi2_k$(new Long(0, 0)) >= 0)
          return toString_2(v, base);
        var tmp$ret$0;
        var tmp0_div = v.ushr_rr8rvr_k$(1);
        tmp$ret$0 = tmp0_div.div_9s1fi3_k$(toLong(base));
        var quotient = tmp$ret$0.shl_po5ip6_k$(1);
        var tmp$ret$1;
        var tmp1_times = quotient;
        tmp$ret$1 = tmp1_times.times_2zfqpc_k$(toLong(base));
        var rem = v.minus_llf5ei_k$(tmp$ret$1);
        if (rem.compareTo_n4fqi2_k$(toLong(base)) >= 0) {
          var tmp$ret$2;
          var tmp2_minus = rem;
          tmp$ret$2 = tmp2_minus.minus_llf5ei_k$(toLong(base));
          rem = tmp$ret$2;
          var tmp$ret$3;
          var tmp3_plus = quotient;
          tmp$ret$3 = tmp3_plus.plus_u6jwas_k$(new Long(1, 0));
          quotient = tmp$ret$3;
        }
        return toString_2(quotient, base) + toString_2(rem, base);
      }
      function doubleToUInt(v) {
        var tmp;
        if (isNaN_0(v)) {
          tmp = _UInt___init__impl__l7qpdl(0);
        } else {
          var tmp$ret$0;
          Companion_getInstance_11();
          var tmp0_toDouble = _UInt___init__impl__l7qpdl(0);
          tmp$ret$0 = uintToDouble(_UInt___get_data__impl__f0vqqw(tmp0_toDouble));
          if (v <= tmp$ret$0) {
            Companion_getInstance_11();
            tmp = _UInt___init__impl__l7qpdl(0);
          } else {
            var tmp$ret$1;
            Companion_getInstance_11();
            var tmp1_toDouble = _UInt___init__impl__l7qpdl(-1);
            tmp$ret$1 = uintToDouble(_UInt___get_data__impl__f0vqqw(tmp1_toDouble));
            if (v >= tmp$ret$1) {
              Companion_getInstance_11();
              tmp = _UInt___init__impl__l7qpdl(-1);
            } else {
              if (v <= IntCompanionObject_getInstance().MAX_VALUE_1) {
                var tmp$ret$2;
                var tmp2_toUInt = numberToInt(v);
                tmp$ret$2 = _UInt___init__impl__l7qpdl(tmp2_toUInt);
                tmp = tmp$ret$2;
              } else {
                var tmp$ret$5;
                var tmp$ret$3;
                var tmp3_toUInt = numberToInt(v - IntCompanionObject_getInstance().MAX_VALUE_1);
                tmp$ret$3 = _UInt___init__impl__l7qpdl(tmp3_toUInt);
                var tmp5_plus = tmp$ret$3;
                var tmp$ret$4;
                var tmp4_toUInt = IntCompanionObject_getInstance().MAX_VALUE_1;
                tmp$ret$4 = _UInt___init__impl__l7qpdl(tmp4_toUInt);
                var tmp6_plus = tmp$ret$4;
                tmp$ret$5 = _UInt___init__impl__l7qpdl(_UInt___get_data__impl__f0vqqw(tmp5_plus) + _UInt___get_data__impl__f0vqqw(tmp6_plus) | 0);
                tmp = tmp$ret$5;
              }
            }
          }
        }
        return tmp;
      }
      function doubleToULong(v) {
        var tmp;
        if (isNaN_0(v)) {
          tmp = _ULong___init__impl__c78o9k(new Long(0, 0));
        } else {
          var tmp$ret$0;
          Companion_getInstance_14();
          var tmp0_toDouble = _ULong___init__impl__c78o9k(new Long(0, 0));
          tmp$ret$0 = ulongToDouble(_ULong___get_data__impl__fggpzb(tmp0_toDouble));
          if (v <= tmp$ret$0) {
            Companion_getInstance_14();
            tmp = _ULong___init__impl__c78o9k(new Long(0, 0));
          } else {
            var tmp$ret$1;
            Companion_getInstance_14();
            var tmp1_toDouble = _ULong___init__impl__c78o9k(new Long(-1, -1));
            tmp$ret$1 = ulongToDouble(_ULong___get_data__impl__fggpzb(tmp1_toDouble));
            if (v >= tmp$ret$1) {
              Companion_getInstance_14();
              tmp = _ULong___init__impl__c78o9k(new Long(-1, -1));
            } else {
              Companion_getInstance_20();
              if (v < new Long(-1, 2147483647).toDouble_ygsx0s_k$()) {
                var tmp$ret$2;
                var tmp2_toULong = numberToLong(v);
                tmp$ret$2 = _ULong___init__impl__c78o9k(tmp2_toULong);
                tmp = tmp$ret$2;
              } else {
                var tmp$ret$4;
                var tmp$ret$3;
                var tmp3_toULong = numberToLong(v - 9223372036854776e3);
                tmp$ret$3 = _ULong___init__impl__c78o9k(tmp3_toULong);
                var tmp4_plus = tmp$ret$3;
                tmp$ret$4 = _ULong___init__impl__c78o9k(_ULong___get_data__impl__fggpzb(tmp4_plus).plus_u6jwas_k$(_ULong___get_data__impl__fggpzb(_ULong___init__impl__c78o9k(new Long(0, -2147483648)))));
                tmp = tmp$ret$4;
              }
            }
          }
        }
        return tmp;
      }
      function ExperimentalUnsignedTypes() {
      }
      ExperimentalUnsignedTypes.prototype.equals = function(other) {
        if (!(other instanceof ExperimentalUnsignedTypes))
          return false;
        var tmp0_other_with_cast = other instanceof ExperimentalUnsignedTypes ? other : THROW_CCE();
        return true;
      };
      ExperimentalUnsignedTypes.prototype.hashCode = function() {
        return 0;
      };
      ExperimentalUnsignedTypes.prototype.toString = function() {
        return "@kotlin.ExperimentalUnsignedTypes()";
      };
      ExperimentalUnsignedTypes.$metadata$ = classMeta("ExperimentalUnsignedTypes", [Annotation]);
      function Annotation() {
      }
      Annotation.$metadata$ = interfaceMeta("Annotation");
      function CharSequence() {
      }
      CharSequence.$metadata$ = interfaceMeta("CharSequence");
      function Comparable() {
      }
      Comparable.$metadata$ = interfaceMeta("Comparable");
      function Iterator_3() {
      }
      Iterator_3.$metadata$ = interfaceMeta("Iterator");
      function MutableIterator() {
      }
      MutableIterator.$metadata$ = interfaceMeta("MutableIterator", [Iterator_3]);
      function MutableListIterator() {
      }
      MutableListIterator.$metadata$ = interfaceMeta("MutableListIterator", [ListIterator, MutableIterator]);
      function ListIterator() {
      }
      ListIterator.$metadata$ = interfaceMeta("ListIterator", [Iterator_3]);
      function Number_0() {
      }
      Number_0.$metadata$ = classMeta("Number");
      function SinceKotlin(version3) {
        this.version_1 = version3;
      }
      SinceKotlin.prototype.get_version_72w4j3_k$ = function() {
        return this.version_1;
      };
      SinceKotlin.prototype.equals = function(other) {
        if (!(other instanceof SinceKotlin))
          return false;
        var tmp0_other_with_cast = other instanceof SinceKotlin ? other : THROW_CCE();
        if (!(this.version_1 === tmp0_other_with_cast.version_1))
          return false;
        return true;
      };
      SinceKotlin.prototype.hashCode = function() {
        return imul(getStringHashCode("version"), 127) ^ getStringHashCode(this.version_1);
      };
      SinceKotlin.prototype.toString = function() {
        return "@kotlin.SinceKotlin(version=" + this.version_1 + ")";
      };
      SinceKotlin.$metadata$ = classMeta("SinceKotlin", [Annotation]);
      function Suppress(names) {
        this.names_1 = names;
      }
      Suppress.prototype.get_names_ivn21r_k$ = function() {
        return this.names_1;
      };
      Suppress.prototype.equals = function(other) {
        if (!(other instanceof Suppress))
          return false;
        var tmp0_other_with_cast = other instanceof Suppress ? other : THROW_CCE();
        if (!contentEquals_7(this.names_1, tmp0_other_with_cast.names_1))
          return false;
        return true;
      };
      Suppress.prototype.hashCode = function() {
        return imul(getStringHashCode("names"), 127) ^ hashCode(this.names_1);
      };
      Suppress.prototype.toString = function() {
        return "@kotlin.Suppress(names=" + toString_1(this.names_1) + ")";
      };
      Suppress.$metadata$ = classMeta("Suppress", [Annotation]);
      function PublishedApi() {
      }
      PublishedApi.prototype.equals = function(other) {
        if (!(other instanceof PublishedApi))
          return false;
        var tmp0_other_with_cast = other instanceof PublishedApi ? other : THROW_CCE();
        return true;
      };
      PublishedApi.prototype.hashCode = function() {
        return 0;
      };
      PublishedApi.prototype.toString = function() {
        return "@kotlin.PublishedApi()";
      };
      PublishedApi.$metadata$ = classMeta("PublishedApi", [Annotation]);
      function ParameterName(name) {
        this.name_1 = name;
      }
      ParameterName.prototype.get_name_woqyms_k$ = function() {
        return this.name_1;
      };
      ParameterName.prototype.equals = function(other) {
        if (!(other instanceof ParameterName))
          return false;
        var tmp0_other_with_cast = other instanceof ParameterName ? other : THROW_CCE();
        if (!(this.name_1 === tmp0_other_with_cast.name_1))
          return false;
        return true;
      };
      ParameterName.prototype.hashCode = function() {
        return imul(getStringHashCode("name"), 127) ^ getStringHashCode(this.name_1);
      };
      ParameterName.prototype.toString = function() {
        return "@kotlin.ParameterName(name=" + this.name_1 + ")";
      };
      ParameterName.$metadata$ = classMeta("ParameterName", [Annotation]);
      function Deprecated_init_$Init$(message, replaceWith, level, $mask0, $marker, $this) {
        if (!(($mask0 & 2) === 0))
          replaceWith = new ReplaceWith("", []);
        if (!(($mask0 & 4) === 0))
          level = DeprecationLevel_WARNING_getInstance();
        Deprecated.call($this, message, replaceWith, level);
        return $this;
      }
      function Deprecated_init_$Create$(message, replaceWith, level, $mask0, $marker) {
        return Deprecated_init_$Init$(message, replaceWith, level, $mask0, $marker, Object.create(Deprecated.prototype));
      }
      function Deprecated(message, replaceWith, level) {
        this.message_1 = message;
        this.replaceWith_1 = replaceWith;
        this.level_1 = level;
      }
      Deprecated.prototype.get_message_h23axq_k$ = function() {
        return this.message_1;
      };
      Deprecated.prototype.get_replaceWith_l0ddm9_k$ = function() {
        return this.replaceWith_1;
      };
      Deprecated.prototype.get_level_ium7h7_k$ = function() {
        return this.level_1;
      };
      Deprecated.prototype.equals = function(other) {
        if (!(other instanceof Deprecated))
          return false;
        var tmp0_other_with_cast = other instanceof Deprecated ? other : THROW_CCE();
        if (!(this.message_1 === tmp0_other_with_cast.message_1))
          return false;
        if (!this.replaceWith_1.equals(tmp0_other_with_cast.replaceWith_1))
          return false;
        if (!this.level_1.equals(tmp0_other_with_cast.level_1))
          return false;
        return true;
      };
      Deprecated.prototype.hashCode = function() {
        var result = imul(getStringHashCode("message"), 127) ^ getStringHashCode(this.message_1);
        result = result + (imul(getStringHashCode("replaceWith"), 127) ^ hashCode(this.replaceWith_1)) | 0;
        result = result + (imul(getStringHashCode("level"), 127) ^ this.level_1.hashCode()) | 0;
        return result;
      };
      Deprecated.prototype.toString = function() {
        return "@kotlin.Deprecated(message=" + this.message_1 + ", replaceWith=" + this.replaceWith_1 + ", level=" + this.level_1 + ")";
      };
      Deprecated.$metadata$ = classMeta("Deprecated", [Annotation]);
      function ReplaceWith(expression, imports) {
        this.expression_1 = expression;
        this.imports_1 = imports;
      }
      ReplaceWith.prototype.get_expression_l5w7j5_k$ = function() {
        return this.expression_1;
      };
      ReplaceWith.prototype.get_imports_x49mdh_k$ = function() {
        return this.imports_1;
      };
      ReplaceWith.prototype.equals = function(other) {
        if (!(other instanceof ReplaceWith))
          return false;
        var tmp0_other_with_cast = other instanceof ReplaceWith ? other : THROW_CCE();
        if (!(this.expression_1 === tmp0_other_with_cast.expression_1))
          return false;
        if (!contentEquals_7(this.imports_1, tmp0_other_with_cast.imports_1))
          return false;
        return true;
      };
      ReplaceWith.prototype.hashCode = function() {
        var result = imul(getStringHashCode("expression"), 127) ^ getStringHashCode(this.expression_1);
        result = result + (imul(getStringHashCode("imports"), 127) ^ hashCode(this.imports_1)) | 0;
        return result;
      };
      ReplaceWith.prototype.toString = function() {
        return "@kotlin.ReplaceWith(expression=" + this.expression_1 + ", imports=" + toString_1(this.imports_1) + ")";
      };
      ReplaceWith.$metadata$ = classMeta("ReplaceWith", [Annotation]);
      function DeprecatedSinceKotlin_init_$Init$(warningSince, errorSince, hiddenSince, $mask0, $marker, $this) {
        if (!(($mask0 & 1) === 0))
          warningSince = "";
        if (!(($mask0 & 2) === 0))
          errorSince = "";
        if (!(($mask0 & 4) === 0))
          hiddenSince = "";
        DeprecatedSinceKotlin.call($this, warningSince, errorSince, hiddenSince);
        return $this;
      }
      function DeprecatedSinceKotlin_init_$Create$(warningSince, errorSince, hiddenSince, $mask0, $marker) {
        return DeprecatedSinceKotlin_init_$Init$(warningSince, errorSince, hiddenSince, $mask0, $marker, Object.create(DeprecatedSinceKotlin.prototype));
      }
      function DeprecatedSinceKotlin(warningSince, errorSince, hiddenSince) {
        this.warningSince_1 = warningSince;
        this.errorSince_1 = errorSince;
        this.hiddenSince_1 = hiddenSince;
      }
      DeprecatedSinceKotlin.prototype.get_warningSince_szk795_k$ = function() {
        return this.warningSince_1;
      };
      DeprecatedSinceKotlin.prototype.get_errorSince_6p3nh7_k$ = function() {
        return this.errorSince_1;
      };
      DeprecatedSinceKotlin.prototype.get_hiddenSince_8z3cp_k$ = function() {
        return this.hiddenSince_1;
      };
      DeprecatedSinceKotlin.prototype.equals = function(other) {
        if (!(other instanceof DeprecatedSinceKotlin))
          return false;
        var tmp0_other_with_cast = other instanceof DeprecatedSinceKotlin ? other : THROW_CCE();
        if (!(this.warningSince_1 === tmp0_other_with_cast.warningSince_1))
          return false;
        if (!(this.errorSince_1 === tmp0_other_with_cast.errorSince_1))
          return false;
        if (!(this.hiddenSince_1 === tmp0_other_with_cast.hiddenSince_1))
          return false;
        return true;
      };
      DeprecatedSinceKotlin.prototype.hashCode = function() {
        var result = imul(getStringHashCode("warningSince"), 127) ^ getStringHashCode(this.warningSince_1);
        result = result + (imul(getStringHashCode("errorSince"), 127) ^ getStringHashCode(this.errorSince_1)) | 0;
        result = result + (imul(getStringHashCode("hiddenSince"), 127) ^ getStringHashCode(this.hiddenSince_1)) | 0;
        return result;
      };
      DeprecatedSinceKotlin.prototype.toString = function() {
        return "@kotlin.DeprecatedSinceKotlin(warningSince=" + this.warningSince_1 + ", errorSince=" + this.errorSince_1 + ", hiddenSince=" + this.hiddenSince_1 + ")";
      };
      DeprecatedSinceKotlin.$metadata$ = classMeta("DeprecatedSinceKotlin", [Annotation]);
      var DeprecationLevel_WARNING_instance;
      var DeprecationLevel_ERROR_instance;
      var DeprecationLevel_HIDDEN_instance;
      function values_3() {
        return [DeprecationLevel_WARNING_getInstance(), DeprecationLevel_ERROR_getInstance(), DeprecationLevel_HIDDEN_getInstance()];
      }
      function valueOf_3(value) {
        switch (value) {
          case "WARNING":
            return DeprecationLevel_WARNING_getInstance();
          case "ERROR":
            return DeprecationLevel_ERROR_getInstance();
          case "HIDDEN":
            return DeprecationLevel_HIDDEN_getInstance();
          default:
            DeprecationLevel_initEntries();
            THROW_ISE();
            break;
        }
      }
      var DeprecationLevel_entriesInitialized;
      function DeprecationLevel_initEntries() {
        if (DeprecationLevel_entriesInitialized)
          return Unit_getInstance();
        DeprecationLevel_entriesInitialized = true;
        DeprecationLevel_WARNING_instance = new DeprecationLevel("WARNING", 0);
        DeprecationLevel_ERROR_instance = new DeprecationLevel("ERROR", 1);
        DeprecationLevel_HIDDEN_instance = new DeprecationLevel("HIDDEN", 2);
      }
      function DeprecationLevel(name, ordinal) {
        Enum.call(this, name, ordinal);
      }
      DeprecationLevel.$metadata$ = classMeta("DeprecationLevel", void 0, void 0, void 0, void 0, Enum.prototype);
      function ExtensionFunctionType() {
      }
      ExtensionFunctionType.prototype.equals = function(other) {
        if (!(other instanceof ExtensionFunctionType))
          return false;
        var tmp0_other_with_cast = other instanceof ExtensionFunctionType ? other : THROW_CCE();
        return true;
      };
      ExtensionFunctionType.prototype.hashCode = function() {
        return 0;
      };
      ExtensionFunctionType.prototype.toString = function() {
        return "@kotlin.ExtensionFunctionType()";
      };
      ExtensionFunctionType.$metadata$ = classMeta("ExtensionFunctionType", [Annotation]);
      function UnsafeVariance() {
      }
      UnsafeVariance.prototype.equals = function(other) {
        if (!(other instanceof UnsafeVariance))
          return false;
        var tmp0_other_with_cast = other instanceof UnsafeVariance ? other : THROW_CCE();
        return true;
      };
      UnsafeVariance.prototype.hashCode = function() {
        return 0;
      };
      UnsafeVariance.prototype.toString = function() {
        return "@kotlin.UnsafeVariance()";
      };
      UnsafeVariance.$metadata$ = classMeta("UnsafeVariance", [Annotation]);
      function DeprecationLevel_WARNING_getInstance() {
        DeprecationLevel_initEntries();
        return DeprecationLevel_WARNING_instance;
      }
      function DeprecationLevel_ERROR_getInstance() {
        DeprecationLevel_initEntries();
        return DeprecationLevel_ERROR_instance;
      }
      function DeprecationLevel_HIDDEN_getInstance() {
        DeprecationLevel_initEntries();
        return DeprecationLevel_HIDDEN_instance;
      }
      function Unit() {
        Unit_instance = this;
      }
      Unit.prototype.toString = function() {
        return "kotlin.Unit";
      };
      Unit.$metadata$ = objectMeta("Unit");
      var Unit_instance;
      function Unit_getInstance() {
        if (Unit_instance == null)
          new Unit();
        return Unit_instance;
      }
      function Target(allowedTargets) {
        this.allowedTargets_1 = allowedTargets;
      }
      Target.prototype.get_allowedTargets_9sf77n_k$ = function() {
        return this.allowedTargets_1;
      };
      Target.prototype.equals = function(other) {
        if (!(other instanceof Target))
          return false;
        var tmp0_other_with_cast = other instanceof Target ? other : THROW_CCE();
        if (!contentEquals_7(this.allowedTargets_1, tmp0_other_with_cast.allowedTargets_1))
          return false;
        return true;
      };
      Target.prototype.hashCode = function() {
        return imul(getStringHashCode("allowedTargets"), 127) ^ hashCode(this.allowedTargets_1);
      };
      Target.prototype.toString = function() {
        return "@kotlin.annotation.Target(allowedTargets=" + toString_1(this.allowedTargets_1) + ")";
      };
      Target.$metadata$ = classMeta("Target", [Annotation]);
      var AnnotationTarget_CLASS_instance;
      var AnnotationTarget_ANNOTATION_CLASS_instance;
      var AnnotationTarget_TYPE_PARAMETER_instance;
      var AnnotationTarget_PROPERTY_instance;
      var AnnotationTarget_FIELD_instance;
      var AnnotationTarget_LOCAL_VARIABLE_instance;
      var AnnotationTarget_VALUE_PARAMETER_instance;
      var AnnotationTarget_CONSTRUCTOR_instance;
      var AnnotationTarget_FUNCTION_instance;
      var AnnotationTarget_PROPERTY_GETTER_instance;
      var AnnotationTarget_PROPERTY_SETTER_instance;
      var AnnotationTarget_TYPE_instance;
      var AnnotationTarget_EXPRESSION_instance;
      var AnnotationTarget_FILE_instance;
      var AnnotationTarget_TYPEALIAS_instance;
      function values_4() {
        return [AnnotationTarget_CLASS_getInstance(), AnnotationTarget_ANNOTATION_CLASS_getInstance(), AnnotationTarget_TYPE_PARAMETER_getInstance(), AnnotationTarget_PROPERTY_getInstance(), AnnotationTarget_FIELD_getInstance(), AnnotationTarget_LOCAL_VARIABLE_getInstance(), AnnotationTarget_VALUE_PARAMETER_getInstance(), AnnotationTarget_CONSTRUCTOR_getInstance(), AnnotationTarget_FUNCTION_getInstance(), AnnotationTarget_PROPERTY_GETTER_getInstance(), AnnotationTarget_PROPERTY_SETTER_getInstance(), AnnotationTarget_TYPE_getInstance(), AnnotationTarget_EXPRESSION_getInstance(), AnnotationTarget_FILE_getInstance(), AnnotationTarget_TYPEALIAS_getInstance()];
      }
      function valueOf_4(value) {
        switch (value) {
          case "CLASS":
            return AnnotationTarget_CLASS_getInstance();
          case "ANNOTATION_CLASS":
            return AnnotationTarget_ANNOTATION_CLASS_getInstance();
          case "TYPE_PARAMETER":
            return AnnotationTarget_TYPE_PARAMETER_getInstance();
          case "PROPERTY":
            return AnnotationTarget_PROPERTY_getInstance();
          case "FIELD":
            return AnnotationTarget_FIELD_getInstance();
          case "LOCAL_VARIABLE":
            return AnnotationTarget_LOCAL_VARIABLE_getInstance();
          case "VALUE_PARAMETER":
            return AnnotationTarget_VALUE_PARAMETER_getInstance();
          case "CONSTRUCTOR":
            return AnnotationTarget_CONSTRUCTOR_getInstance();
          case "FUNCTION":
            return AnnotationTarget_FUNCTION_getInstance();
          case "PROPERTY_GETTER":
            return AnnotationTarget_PROPERTY_GETTER_getInstance();
          case "PROPERTY_SETTER":
            return AnnotationTarget_PROPERTY_SETTER_getInstance();
          case "TYPE":
            return AnnotationTarget_TYPE_getInstance();
          case "EXPRESSION":
            return AnnotationTarget_EXPRESSION_getInstance();
          case "FILE":
            return AnnotationTarget_FILE_getInstance();
          case "TYPEALIAS":
            return AnnotationTarget_TYPEALIAS_getInstance();
          default:
            AnnotationTarget_initEntries();
            THROW_ISE();
            break;
        }
      }
      var AnnotationTarget_entriesInitialized;
      function AnnotationTarget_initEntries() {
        if (AnnotationTarget_entriesInitialized)
          return Unit_getInstance();
        AnnotationTarget_entriesInitialized = true;
        AnnotationTarget_CLASS_instance = new AnnotationTarget("CLASS", 0);
        AnnotationTarget_ANNOTATION_CLASS_instance = new AnnotationTarget("ANNOTATION_CLASS", 1);
        AnnotationTarget_TYPE_PARAMETER_instance = new AnnotationTarget("TYPE_PARAMETER", 2);
        AnnotationTarget_PROPERTY_instance = new AnnotationTarget("PROPERTY", 3);
        AnnotationTarget_FIELD_instance = new AnnotationTarget("FIELD", 4);
        AnnotationTarget_LOCAL_VARIABLE_instance = new AnnotationTarget("LOCAL_VARIABLE", 5);
        AnnotationTarget_VALUE_PARAMETER_instance = new AnnotationTarget("VALUE_PARAMETER", 6);
        AnnotationTarget_CONSTRUCTOR_instance = new AnnotationTarget("CONSTRUCTOR", 7);
        AnnotationTarget_FUNCTION_instance = new AnnotationTarget("FUNCTION", 8);
        AnnotationTarget_PROPERTY_GETTER_instance = new AnnotationTarget("PROPERTY_GETTER", 9);
        AnnotationTarget_PROPERTY_SETTER_instance = new AnnotationTarget("PROPERTY_SETTER", 10);
        AnnotationTarget_TYPE_instance = new AnnotationTarget("TYPE", 11);
        AnnotationTarget_EXPRESSION_instance = new AnnotationTarget("EXPRESSION", 12);
        AnnotationTarget_FILE_instance = new AnnotationTarget("FILE", 13);
        AnnotationTarget_TYPEALIAS_instance = new AnnotationTarget("TYPEALIAS", 14);
      }
      function AnnotationTarget(name, ordinal) {
        Enum.call(this, name, ordinal);
      }
      AnnotationTarget.$metadata$ = classMeta("AnnotationTarget", void 0, void 0, void 0, void 0, Enum.prototype);
      function MustBeDocumented() {
      }
      MustBeDocumented.prototype.equals = function(other) {
        if (!(other instanceof MustBeDocumented))
          return false;
        var tmp0_other_with_cast = other instanceof MustBeDocumented ? other : THROW_CCE();
        return true;
      };
      MustBeDocumented.prototype.hashCode = function() {
        return 0;
      };
      MustBeDocumented.prototype.toString = function() {
        return "@kotlin.annotation.MustBeDocumented()";
      };
      MustBeDocumented.$metadata$ = classMeta("MustBeDocumented", [Annotation]);
      function Retention_init_$Init$(value, $mask0, $marker, $this) {
        if (!(($mask0 & 1) === 0))
          value = AnnotationRetention_RUNTIME_getInstance();
        Retention.call($this, value);
        return $this;
      }
      function Retention_init_$Create$(value, $mask0, $marker) {
        return Retention_init_$Init$(value, $mask0, $marker, Object.create(Retention.prototype));
      }
      function Retention(value) {
        this.value_1 = value;
      }
      Retention.prototype.get_value_j01efc_k$ = function() {
        return this.value_1;
      };
      Retention.prototype.equals = function(other) {
        if (!(other instanceof Retention))
          return false;
        var tmp0_other_with_cast = other instanceof Retention ? other : THROW_CCE();
        if (!this.value_1.equals(tmp0_other_with_cast.value_1))
          return false;
        return true;
      };
      Retention.prototype.hashCode = function() {
        return imul(getStringHashCode("value"), 127) ^ this.value_1.hashCode();
      };
      Retention.prototype.toString = function() {
        return "@kotlin.annotation.Retention(value=" + this.value_1 + ")";
      };
      Retention.$metadata$ = classMeta("Retention", [Annotation]);
      var AnnotationRetention_SOURCE_instance;
      var AnnotationRetention_BINARY_instance;
      var AnnotationRetention_RUNTIME_instance;
      function values_5() {
        return [AnnotationRetention_SOURCE_getInstance(), AnnotationRetention_BINARY_getInstance(), AnnotationRetention_RUNTIME_getInstance()];
      }
      function valueOf_5(value) {
        switch (value) {
          case "SOURCE":
            return AnnotationRetention_SOURCE_getInstance();
          case "BINARY":
            return AnnotationRetention_BINARY_getInstance();
          case "RUNTIME":
            return AnnotationRetention_RUNTIME_getInstance();
          default:
            AnnotationRetention_initEntries();
            THROW_ISE();
            break;
        }
      }
      var AnnotationRetention_entriesInitialized;
      function AnnotationRetention_initEntries() {
        if (AnnotationRetention_entriesInitialized)
          return Unit_getInstance();
        AnnotationRetention_entriesInitialized = true;
        AnnotationRetention_SOURCE_instance = new AnnotationRetention("SOURCE", 0);
        AnnotationRetention_BINARY_instance = new AnnotationRetention("BINARY", 1);
        AnnotationRetention_RUNTIME_instance = new AnnotationRetention("RUNTIME", 2);
      }
      function AnnotationRetention(name, ordinal) {
        Enum.call(this, name, ordinal);
      }
      AnnotationRetention.$metadata$ = classMeta("AnnotationRetention", void 0, void 0, void 0, void 0, Enum.prototype);
      function AnnotationTarget_CLASS_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_CLASS_instance;
      }
      function AnnotationTarget_ANNOTATION_CLASS_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_ANNOTATION_CLASS_instance;
      }
      function AnnotationTarget_TYPE_PARAMETER_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_TYPE_PARAMETER_instance;
      }
      function AnnotationTarget_PROPERTY_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_PROPERTY_instance;
      }
      function AnnotationTarget_FIELD_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_FIELD_instance;
      }
      function AnnotationTarget_LOCAL_VARIABLE_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_LOCAL_VARIABLE_instance;
      }
      function AnnotationTarget_VALUE_PARAMETER_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_VALUE_PARAMETER_instance;
      }
      function AnnotationTarget_CONSTRUCTOR_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_CONSTRUCTOR_instance;
      }
      function AnnotationTarget_FUNCTION_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_FUNCTION_instance;
      }
      function AnnotationTarget_PROPERTY_GETTER_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_PROPERTY_GETTER_instance;
      }
      function AnnotationTarget_PROPERTY_SETTER_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_PROPERTY_SETTER_instance;
      }
      function AnnotationTarget_TYPE_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_TYPE_instance;
      }
      function AnnotationTarget_EXPRESSION_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_EXPRESSION_instance;
      }
      function AnnotationTarget_FILE_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_FILE_instance;
      }
      function AnnotationTarget_TYPEALIAS_getInstance() {
        AnnotationTarget_initEntries();
        return AnnotationTarget_TYPEALIAS_instance;
      }
      function AnnotationRetention_SOURCE_getInstance() {
        AnnotationRetention_initEntries();
        return AnnotationRetention_SOURCE_instance;
      }
      function AnnotationRetention_BINARY_getInstance() {
        AnnotationRetention_initEntries();
        return AnnotationRetention_BINARY_instance;
      }
      function AnnotationRetention_RUNTIME_getInstance() {
        AnnotationRetention_initEntries();
        return AnnotationRetention_RUNTIME_instance;
      }
      function IntrinsicConstEvaluation() {
      }
      IntrinsicConstEvaluation.prototype.equals = function(other) {
        if (!(other instanceof IntrinsicConstEvaluation))
          return false;
        var tmp0_other_with_cast = other instanceof IntrinsicConstEvaluation ? other : THROW_CCE();
        return true;
      };
      IntrinsicConstEvaluation.prototype.hashCode = function() {
        return 0;
      };
      IntrinsicConstEvaluation.prototype.toString = function() {
        return "@kotlin.internal.IntrinsicConstEvaluation()";
      };
      IntrinsicConstEvaluation.$metadata$ = classMeta("IntrinsicConstEvaluation", [Annotation]);
      function ByteCompanionObject() {
        ByteCompanionObject_instance = this;
        this.MIN_VALUE_1 = -128;
        this.MAX_VALUE_1 = 127;
        this.SIZE_BYTES_1 = 1;
        this.SIZE_BITS_1 = 8;
      }
      ByteCompanionObject.prototype.get_MIN_VALUE_7nmmor_k$ = function() {
        return this.MIN_VALUE_1;
      };
      ByteCompanionObject.prototype.get_MAX_VALUE_54a9lf_k$ = function() {
        return this.MAX_VALUE_1;
      };
      ByteCompanionObject.prototype.get_SIZE_BYTES_qphg4q_k$ = function() {
        return this.SIZE_BYTES_1;
      };
      ByteCompanionObject.prototype.get_SIZE_BITS_7qhjj9_k$ = function() {
        return this.SIZE_BITS_1;
      };
      ByteCompanionObject.$metadata$ = objectMeta("ByteCompanionObject");
      Object.defineProperty(ByteCompanionObject.prototype, "MIN_VALUE", {
        configurable: true,
        get: ByteCompanionObject.prototype.get_MIN_VALUE_7nmmor_k$
      });
      Object.defineProperty(ByteCompanionObject.prototype, "MAX_VALUE", {
        configurable: true,
        get: ByteCompanionObject.prototype.get_MAX_VALUE_54a9lf_k$
      });
      Object.defineProperty(ByteCompanionObject.prototype, "SIZE_BYTES", {
        configurable: true,
        get: ByteCompanionObject.prototype.get_SIZE_BYTES_qphg4q_k$
      });
      Object.defineProperty(ByteCompanionObject.prototype, "SIZE_BITS", {
        configurable: true,
        get: ByteCompanionObject.prototype.get_SIZE_BITS_7qhjj9_k$
      });
      var ByteCompanionObject_instance;
      function ByteCompanionObject_getInstance() {
        if (ByteCompanionObject_instance == null)
          new ByteCompanionObject();
        return ByteCompanionObject_instance;
      }
      function ShortCompanionObject() {
        ShortCompanionObject_instance = this;
        this.MIN_VALUE_1 = -32768;
        this.MAX_VALUE_1 = 32767;
        this.SIZE_BYTES_1 = 2;
        this.SIZE_BITS_1 = 16;
      }
      ShortCompanionObject.prototype.get_MIN_VALUE_7nmmor_k$ = function() {
        return this.MIN_VALUE_1;
      };
      ShortCompanionObject.prototype.get_MAX_VALUE_54a9lf_k$ = function() {
        return this.MAX_VALUE_1;
      };
      ShortCompanionObject.prototype.get_SIZE_BYTES_qphg4q_k$ = function() {
        return this.SIZE_BYTES_1;
      };
      ShortCompanionObject.prototype.get_SIZE_BITS_7qhjj9_k$ = function() {
        return this.SIZE_BITS_1;
      };
      ShortCompanionObject.$metadata$ = objectMeta("ShortCompanionObject");
      Object.defineProperty(ShortCompanionObject.prototype, "MIN_VALUE", {
        configurable: true,
        get: ShortCompanionObject.prototype.get_MIN_VALUE_7nmmor_k$
      });
      Object.defineProperty(ShortCompanionObject.prototype, "MAX_VALUE", {
        configurable: true,
        get: ShortCompanionObject.prototype.get_MAX_VALUE_54a9lf_k$
      });
      Object.defineProperty(ShortCompanionObject.prototype, "SIZE_BYTES", {
        configurable: true,
        get: ShortCompanionObject.prototype.get_SIZE_BYTES_qphg4q_k$
      });
      Object.defineProperty(ShortCompanionObject.prototype, "SIZE_BITS", {
        configurable: true,
        get: ShortCompanionObject.prototype.get_SIZE_BITS_7qhjj9_k$
      });
      var ShortCompanionObject_instance;
      function ShortCompanionObject_getInstance() {
        if (ShortCompanionObject_instance == null)
          new ShortCompanionObject();
        return ShortCompanionObject_instance;
      }
      function IntCompanionObject() {
        IntCompanionObject_instance = this;
        this.MIN_VALUE_1 = -2147483648;
        this.MAX_VALUE_1 = 2147483647;
        this.SIZE_BYTES_1 = 4;
        this.SIZE_BITS_1 = 32;
      }
      IntCompanionObject.prototype.get_MIN_VALUE_7nmmor_k$ = function() {
        return this.MIN_VALUE_1;
      };
      IntCompanionObject.prototype.get_MAX_VALUE_54a9lf_k$ = function() {
        return this.MAX_VALUE_1;
      };
      IntCompanionObject.prototype.get_SIZE_BYTES_qphg4q_k$ = function() {
        return this.SIZE_BYTES_1;
      };
      IntCompanionObject.prototype.get_SIZE_BITS_7qhjj9_k$ = function() {
        return this.SIZE_BITS_1;
      };
      IntCompanionObject.$metadata$ = objectMeta("IntCompanionObject");
      Object.defineProperty(IntCompanionObject.prototype, "MIN_VALUE", {
        configurable: true,
        get: IntCompanionObject.prototype.get_MIN_VALUE_7nmmor_k$
      });
      Object.defineProperty(IntCompanionObject.prototype, "MAX_VALUE", {
        configurable: true,
        get: IntCompanionObject.prototype.get_MAX_VALUE_54a9lf_k$
      });
      Object.defineProperty(IntCompanionObject.prototype, "SIZE_BYTES", {
        configurable: true,
        get: IntCompanionObject.prototype.get_SIZE_BYTES_qphg4q_k$
      });
      Object.defineProperty(IntCompanionObject.prototype, "SIZE_BITS", {
        configurable: true,
        get: IntCompanionObject.prototype.get_SIZE_BITS_7qhjj9_k$
      });
      var IntCompanionObject_instance;
      function IntCompanionObject_getInstance() {
        if (IntCompanionObject_instance == null)
          new IntCompanionObject();
        return IntCompanionObject_instance;
      }
      function FloatCompanionObject() {
        FloatCompanionObject_instance = this;
        this.MIN_VALUE_1 = 14e-46;
        this.MAX_VALUE_1 = 34028235e31;
        this.POSITIVE_INFINITY_1 = Infinity;
        this.NEGATIVE_INFINITY_1 = -Infinity;
        this.NaN_1 = NaN;
        this.SIZE_BYTES_1 = 4;
        this.SIZE_BITS_1 = 32;
      }
      FloatCompanionObject.prototype.get_MIN_VALUE_7nmmor_k$ = function() {
        return this.MIN_VALUE_1;
      };
      FloatCompanionObject.prototype.get_MAX_VALUE_54a9lf_k$ = function() {
        return this.MAX_VALUE_1;
      };
      FloatCompanionObject.prototype.get_POSITIVE_INFINITY_yq30fv_k$ = function() {
        return this.POSITIVE_INFINITY_1;
      };
      FloatCompanionObject.prototype.get_NEGATIVE_INFINITY_e9bp9z_k$ = function() {
        return this.NEGATIVE_INFINITY_1;
      };
      FloatCompanionObject.prototype.get_NaN_18jnv2_k$ = function() {
        return this.NaN_1;
      };
      FloatCompanionObject.prototype.get_SIZE_BYTES_qphg4q_k$ = function() {
        return this.SIZE_BYTES_1;
      };
      FloatCompanionObject.prototype.get_SIZE_BITS_7qhjj9_k$ = function() {
        return this.SIZE_BITS_1;
      };
      FloatCompanionObject.$metadata$ = objectMeta("FloatCompanionObject");
      Object.defineProperty(FloatCompanionObject.prototype, "MIN_VALUE", {
        configurable: true,
        get: FloatCompanionObject.prototype.get_MIN_VALUE_7nmmor_k$
      });
      Object.defineProperty(FloatCompanionObject.prototype, "MAX_VALUE", {
        configurable: true,
        get: FloatCompanionObject.prototype.get_MAX_VALUE_54a9lf_k$
      });
      Object.defineProperty(FloatCompanionObject.prototype, "POSITIVE_INFINITY", {
        configurable: true,
        get: FloatCompanionObject.prototype.get_POSITIVE_INFINITY_yq30fv_k$
      });
      Object.defineProperty(FloatCompanionObject.prototype, "NEGATIVE_INFINITY", {
        configurable: true,
        get: FloatCompanionObject.prototype.get_NEGATIVE_INFINITY_e9bp9z_k$
      });
      Object.defineProperty(FloatCompanionObject.prototype, "NaN", {
        configurable: true,
        get: FloatCompanionObject.prototype.get_NaN_18jnv2_k$
      });
      Object.defineProperty(FloatCompanionObject.prototype, "SIZE_BYTES", {
        configurable: true,
        get: FloatCompanionObject.prototype.get_SIZE_BYTES_qphg4q_k$
      });
      Object.defineProperty(FloatCompanionObject.prototype, "SIZE_BITS", {
        configurable: true,
        get: FloatCompanionObject.prototype.get_SIZE_BITS_7qhjj9_k$
      });
      var FloatCompanionObject_instance;
      function FloatCompanionObject_getInstance() {
        if (FloatCompanionObject_instance == null)
          new FloatCompanionObject();
        return FloatCompanionObject_instance;
      }
      function DoubleCompanionObject() {
        DoubleCompanionObject_instance = this;
        this.MIN_VALUE_1 = 5e-324;
        this.MAX_VALUE_1 = 17976931348623157e292;
        this.POSITIVE_INFINITY_1 = Infinity;
        this.NEGATIVE_INFINITY_1 = -Infinity;
        this.NaN_1 = NaN;
        this.SIZE_BYTES_1 = 8;
        this.SIZE_BITS_1 = 64;
      }
      DoubleCompanionObject.prototype.get_MIN_VALUE_7nmmor_k$ = function() {
        return this.MIN_VALUE_1;
      };
      DoubleCompanionObject.prototype.get_MAX_VALUE_54a9lf_k$ = function() {
        return this.MAX_VALUE_1;
      };
      DoubleCompanionObject.prototype.get_POSITIVE_INFINITY_yq30fv_k$ = function() {
        return this.POSITIVE_INFINITY_1;
      };
      DoubleCompanionObject.prototype.get_NEGATIVE_INFINITY_e9bp9z_k$ = function() {
        return this.NEGATIVE_INFINITY_1;
      };
      DoubleCompanionObject.prototype.get_NaN_18jnv2_k$ = function() {
        return this.NaN_1;
      };
      DoubleCompanionObject.prototype.get_SIZE_BYTES_qphg4q_k$ = function() {
        return this.SIZE_BYTES_1;
      };
      DoubleCompanionObject.prototype.get_SIZE_BITS_7qhjj9_k$ = function() {
        return this.SIZE_BITS_1;
      };
      DoubleCompanionObject.$metadata$ = objectMeta("DoubleCompanionObject");
      Object.defineProperty(DoubleCompanionObject.prototype, "MIN_VALUE", {
        configurable: true,
        get: DoubleCompanionObject.prototype.get_MIN_VALUE_7nmmor_k$
      });
      Object.defineProperty(DoubleCompanionObject.prototype, "MAX_VALUE", {
        configurable: true,
        get: DoubleCompanionObject.prototype.get_MAX_VALUE_54a9lf_k$
      });
      Object.defineProperty(DoubleCompanionObject.prototype, "POSITIVE_INFINITY", {
        configurable: true,
        get: DoubleCompanionObject.prototype.get_POSITIVE_INFINITY_yq30fv_k$
      });
      Object.defineProperty(DoubleCompanionObject.prototype, "NEGATIVE_INFINITY", {
        configurable: true,
        get: DoubleCompanionObject.prototype.get_NEGATIVE_INFINITY_e9bp9z_k$
      });
      Object.defineProperty(DoubleCompanionObject.prototype, "NaN", {
        configurable: true,
        get: DoubleCompanionObject.prototype.get_NaN_18jnv2_k$
      });
      Object.defineProperty(DoubleCompanionObject.prototype, "SIZE_BYTES", {
        configurable: true,
        get: DoubleCompanionObject.prototype.get_SIZE_BYTES_qphg4q_k$
      });
      Object.defineProperty(DoubleCompanionObject.prototype, "SIZE_BITS", {
        configurable: true,
        get: DoubleCompanionObject.prototype.get_SIZE_BITS_7qhjj9_k$
      });
      var DoubleCompanionObject_instance;
      function DoubleCompanionObject_getInstance() {
        if (DoubleCompanionObject_instance == null)
          new DoubleCompanionObject();
        return DoubleCompanionObject_instance;
      }
      function StringCompanionObject() {
        StringCompanionObject_instance = this;
      }
      StringCompanionObject.$metadata$ = objectMeta("StringCompanionObject");
      var StringCompanionObject_instance;
      function StringCompanionObject_getInstance() {
        if (StringCompanionObject_instance == null)
          new StringCompanionObject();
        return StringCompanionObject_instance;
      }
      function BooleanCompanionObject() {
        BooleanCompanionObject_instance = this;
      }
      BooleanCompanionObject.$metadata$ = objectMeta("BooleanCompanionObject");
      var BooleanCompanionObject_instance;
      function BooleanCompanionObject_getInstance() {
        if (BooleanCompanionObject_instance == null)
          new BooleanCompanionObject();
        return BooleanCompanionObject_instance;
      }
      function Comparator() {
      }
      Comparator.$metadata$ = interfaceMeta("Comparator");
      function JsQualifier(value) {
        this.value_1 = value;
      }
      JsQualifier.prototype.get_value_j01efc_k$ = function() {
        return this.value_1;
      };
      JsQualifier.prototype.equals = function(other) {
        if (!(other instanceof JsQualifier))
          return false;
        var tmp0_other_with_cast = other instanceof JsQualifier ? other : THROW_CCE();
        if (!(this.value_1 === tmp0_other_with_cast.value_1))
          return false;
        return true;
      };
      JsQualifier.prototype.hashCode = function() {
        return imul(getStringHashCode("value"), 127) ^ getStringHashCode(this.value_1);
      };
      JsQualifier.prototype.toString = function() {
        return "@kotlin.js.JsQualifier(value=" + this.value_1 + ")";
      };
      JsQualifier.$metadata$ = classMeta("JsQualifier", [Annotation]);
      function JsName(name) {
        this.name_1 = name;
      }
      JsName.prototype.get_name_woqyms_k$ = function() {
        return this.name_1;
      };
      JsName.prototype.equals = function(other) {
        if (!(other instanceof JsName))
          return false;
        var tmp0_other_with_cast = other instanceof JsName ? other : THROW_CCE();
        if (!(this.name_1 === tmp0_other_with_cast.name_1))
          return false;
        return true;
      };
      JsName.prototype.hashCode = function() {
        return imul(getStringHashCode("name"), 127) ^ getStringHashCode(this.name_1);
      };
      JsName.prototype.toString = function() {
        return "@kotlin.js.JsName(name=" + this.name_1 + ")";
      };
      JsName.$metadata$ = classMeta("JsName", [Annotation]);
      function JsExport() {
      }
      JsExport.prototype.equals = function(other) {
        if (!(other instanceof JsExport))
          return false;
        var tmp0_other_with_cast = other instanceof JsExport ? other : THROW_CCE();
        return true;
      };
      JsExport.prototype.hashCode = function() {
        return 0;
      };
      JsExport.prototype.toString = function() {
        return "@kotlin.js.JsExport()";
      };
      JsExport.$metadata$ = classMeta("JsExport", [Annotation]);
      function EagerInitialization() {
      }
      EagerInitialization.prototype.equals = function(other) {
        if (!(other instanceof EagerInitialization))
          return false;
        var tmp0_other_with_cast = other instanceof EagerInitialization ? other : THROW_CCE();
        return true;
      };
      EagerInitialization.prototype.hashCode = function() {
        return 0;
      };
      EagerInitialization.prototype.toString = function() {
        return "@kotlin.js.EagerInitialization()";
      };
      EagerInitialization.$metadata$ = classMeta("EagerInitialization", [Annotation]);
      function toTypedArray(_this__u8e3s4) {
        return copyToArray(_this__u8e3s4);
      }
      function copyToArray(collection) {
        var tmp;
        var tmp$ret$0;
        tmp$ret$0 = collection;
        if (tmp$ret$0.toArray !== void 0) {
          var tmp$ret$2;
          var tmp$ret$1;
          tmp$ret$1 = collection;
          var tmp0_unsafeCast = tmp$ret$1.toArray();
          tmp$ret$2 = tmp0_unsafeCast;
          tmp = tmp$ret$2;
        } else {
          var tmp$ret$4;
          var tmp1_unsafeCast = copyToArrayImpl(collection);
          var tmp$ret$3;
          tmp$ret$3 = tmp1_unsafeCast;
          tmp$ret$4 = tmp$ret$3;
          tmp = tmp$ret$4;
        }
        return tmp;
      }
      function copyToArrayImpl(collection) {
        var tmp$ret$0;
        tmp$ret$0 = [];
        var array3 = tmp$ret$0;
        var iterator = collection.iterator_jk1svi_k$();
        while (iterator.hasNext_bitz1p_k$()) {
          var tmp$ret$1;
          tmp$ret$1 = array3;
          tmp$ret$1.push(iterator.next_20eer_k$());
        }
        return array3;
      }
      function arrayCopy(source, destination, destinationOffset, startIndex, endIndex) {
        Companion_getInstance().checkRangeIndexes_5hjybp_k$(startIndex, endIndex, source.length);
        var rangeSize = endIndex - startIndex | 0;
        Companion_getInstance().checkRangeIndexes_5hjybp_k$(destinationOffset, destinationOffset + rangeSize | 0, destination.length);
        if (isView(destination) ? isView(source) : false) {
          var tmp$ret$0;
          tmp$ret$0 = source;
          var subrange = tmp$ret$0.subarray(startIndex, endIndex);
          var tmp$ret$1;
          tmp$ret$1 = destination;
          tmp$ret$1.set(subrange, destinationOffset);
        } else {
          if (!(source === destination) ? true : destinationOffset <= startIndex) {
            var inductionVariable = 0;
            if (inductionVariable < rangeSize)
              do {
                var index = inductionVariable;
                inductionVariable = inductionVariable + 1 | 0;
                destination[destinationOffset + index | 0] = source[startIndex + index | 0];
              } while (inductionVariable < rangeSize);
          } else {
            var inductionVariable_0 = rangeSize - 1 | 0;
            if (0 <= inductionVariable_0)
              do {
                var index_0 = inductionVariable_0;
                inductionVariable_0 = inductionVariable_0 + -1 | 0;
                destination[destinationOffset + index_0 | 0] = source[startIndex + index_0 | 0];
              } while (0 <= inductionVariable_0);
          }
        }
      }
      function copyToExistingArrayImpl(collection, array3) {
        if (array3.length < collection.get_size_woubt6_k$()) {
          var tmp$ret$1;
          var tmp0_unsafeCast = copyToArrayImpl(collection);
          var tmp$ret$0;
          tmp$ret$0 = tmp0_unsafeCast;
          tmp$ret$1 = tmp$ret$0;
          return tmp$ret$1;
        }
        var iterator = collection.iterator_jk1svi_k$();
        var index = 0;
        while (iterator.hasNext_bitz1p_k$()) {
          var tmp0 = index;
          index = tmp0 + 1 | 0;
          var tmp$ret$3;
          var tmp1_unsafeCast = iterator.next_20eer_k$();
          var tmp$ret$2;
          tmp$ret$2 = tmp1_unsafeCast;
          tmp$ret$3 = tmp$ret$2;
          array3[tmp0] = tmp$ret$3;
        }
        if (index < array3.length) {
          var tmp = index;
          var tmp$ret$5;
          var tmp$ret$4;
          tmp$ret$4 = null;
          tmp$ret$5 = tmp$ret$4;
          array3[tmp] = tmp$ret$5;
        }
        return array3;
      }
      function AbstractMutableCollection$removeAll$lambda($elements) {
        return function(it) {
          return $elements.contains_2ehdt1_k$(it);
        };
      }
      function AbstractMutableCollection$retainAll$lambda($elements) {
        return function(it) {
          return !$elements.contains_2ehdt1_k$(it);
        };
      }
      function AbstractMutableCollection() {
        AbstractCollection.call(this);
      }
      AbstractMutableCollection.prototype.remove_8hbkc6_k$ = function(element) {
        this.checkIsMutable_h4zzmr_k$();
        var iterator = this.iterator_jk1svi_k$();
        while (iterator.hasNext_bitz1p_k$()) {
          if (equals(iterator.next_20eer_k$(), element)) {
            iterator.remove_le47v1_k$();
            return true;
          }
        }
        return false;
      };
      AbstractMutableCollection.prototype.addAll_oxxjjk_k$ = function(elements) {
        this.checkIsMutable_h4zzmr_k$();
        var modified = false;
        var tmp0_iterator = elements.iterator_jk1svi_k$();
        while (tmp0_iterator.hasNext_bitz1p_k$()) {
          var element = tmp0_iterator.next_20eer_k$();
          if (this.add_1j60pz_k$(element))
            modified = true;
        }
        return modified;
      };
      AbstractMutableCollection.prototype.removeAll_99to5v_k$ = function(elements) {
        this.checkIsMutable_h4zzmr_k$();
        var tmp = isInterface(this, MutableIterable) ? this : THROW_CCE();
        return removeAll_0(tmp, AbstractMutableCollection$removeAll$lambda(elements));
      };
      AbstractMutableCollection.prototype.retainAll_j44sd0_k$ = function(elements) {
        this.checkIsMutable_h4zzmr_k$();
        var tmp = isInterface(this, MutableIterable) ? this : THROW_CCE();
        return removeAll_0(tmp, AbstractMutableCollection$retainAll$lambda(elements));
      };
      AbstractMutableCollection.prototype.clear_j9y8zo_k$ = function() {
        this.checkIsMutable_h4zzmr_k$();
        var iterator = this.iterator_jk1svi_k$();
        while (iterator.hasNext_bitz1p_k$()) {
          iterator.next_20eer_k$();
          iterator.remove_le47v1_k$();
        }
      };
      AbstractMutableCollection.prototype.toJSON = function() {
        return this.toArray();
      };
      AbstractMutableCollection.prototype.checkIsMutable_h4zzmr_k$ = function() {
      };
      AbstractMutableCollection.$metadata$ = classMeta("AbstractMutableCollection", [MutableCollection], void 0, void 0, void 0, AbstractCollection.prototype);
      function _get_list__d9tsa5_0($this) {
        return $this.list_1;
      }
      function _get_fromIndex__987b49_0($this) {
        return $this.fromIndex_1;
      }
      function _set__size__bau3qd_0($this, _set____db54di) {
        $this._size_1 = _set____db54di;
      }
      function _get__size__kqacr3_0($this) {
        return $this._size_1;
      }
      function IteratorImpl_0($outer) {
        this.$this_1 = $outer;
        this.index_1 = 0;
        this.last_1 = -1;
      }
      IteratorImpl_0.prototype.set_index_eknhut_k$ = function(_set____db54di) {
        this.index_1 = _set____db54di;
      };
      IteratorImpl_0.prototype.get_index_it478p_k$ = function() {
        return this.index_1;
      };
      IteratorImpl_0.prototype.set_last_3ufkar_k$ = function(_set____db54di) {
        this.last_1 = _set____db54di;
      };
      IteratorImpl_0.prototype.get_last_wopotb_k$ = function() {
        return this.last_1;
      };
      IteratorImpl_0.prototype.hasNext_bitz1p_k$ = function() {
        return this.index_1 < this.$this_1.get_size_woubt6_k$();
      };
      IteratorImpl_0.prototype.next_20eer_k$ = function() {
        if (!this.hasNext_bitz1p_k$())
          throw NoSuchElementException_init_$Create$();
        var tmp = this;
        var tmp0_this = this;
        var tmp1 = tmp0_this.index_1;
        tmp0_this.index_1 = tmp1 + 1 | 0;
        tmp.last_1 = tmp1;
        return this.$this_1.get_fkrdnv_k$(this.last_1);
      };
      IteratorImpl_0.prototype.remove_le47v1_k$ = function() {
        var tmp0_check = !(this.last_1 === -1);
        if (!tmp0_check) {
          var tmp$ret$0;
          tmp$ret$0 = "Call next() or previous() before removing element from the iterator.";
          var message = tmp$ret$0;
          throw IllegalStateException_init_$Create$_0(toString_1(message));
        }
        this.$this_1.removeAt_qvpkxi_k$(this.last_1);
        this.index_1 = this.last_1;
        this.last_1 = -1;
      };
      IteratorImpl_0.$metadata$ = classMeta("IteratorImpl", [MutableIterator]);
      function ListIteratorImpl_0($outer, index) {
        this.$this_2 = $outer;
        IteratorImpl_0.call(this, $outer);
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this.$this_2.get_size_woubt6_k$());
        this.index_1 = index;
      }
      ListIteratorImpl_0.prototype.hasPrevious_qh0629_k$ = function() {
        return this.index_1 > 0;
      };
      ListIteratorImpl_0.prototype.nextIndex_jshxun_k$ = function() {
        return this.index_1;
      };
      ListIteratorImpl_0.prototype.previous_l2dfd5_k$ = function() {
        if (!this.hasPrevious_qh0629_k$())
          throw NoSuchElementException_init_$Create$();
        var tmp = this;
        var tmp0_this = this;
        tmp0_this.index_1 = tmp0_this.index_1 - 1 | 0;
        tmp.last_1 = tmp0_this.index_1;
        return this.$this_2.get_fkrdnv_k$(this.last_1);
      };
      ListIteratorImpl_0.prototype.previousIndex_4qtyw5_k$ = function() {
        return this.index_1 - 1 | 0;
      };
      ListIteratorImpl_0.prototype.add_8zjh9m_k$ = function(element) {
        this.$this_2.add_ydlf05_k$(this.index_1, element);
        var tmp0_this = this;
        var tmp1 = tmp0_this.index_1;
        tmp0_this.index_1 = tmp1 + 1 | 0;
        this.last_1 = -1;
      };
      ListIteratorImpl_0.prototype.add_sf7wgr_k$ = function(element) {
        return this.add_8zjh9m_k$((element == null ? true : isObject3(element)) ? element : THROW_CCE());
      };
      ListIteratorImpl_0.prototype.set_y85lex_k$ = function(element) {
        var tmp0_check = !(this.last_1 === -1);
        if (!tmp0_check) {
          var tmp$ret$0;
          tmp$ret$0 = "Call next() or previous() before updating element value with the iterator.";
          var message = tmp$ret$0;
          throw IllegalStateException_init_$Create$_0(toString_1(message));
        }
        this.$this_2.set_meu351_k$(this.last_1, element);
      };
      ListIteratorImpl_0.prototype.set_hda1d2_k$ = function(element) {
        return this.set_y85lex_k$((element == null ? true : isObject3(element)) ? element : THROW_CCE());
      };
      ListIteratorImpl_0.$metadata$ = classMeta("ListIteratorImpl", [MutableListIterator], void 0, void 0, void 0, IteratorImpl_0.prototype);
      function SubList_0(list, fromIndex, toIndex) {
        AbstractMutableList.call(this);
        this.list_1 = list;
        this.fromIndex_1 = fromIndex;
        this._size_1 = 0;
        Companion_getInstance().checkRangeIndexes_5hjybp_k$(this.fromIndex_1, toIndex, this.list_1.get_size_woubt6_k$());
        this._size_1 = toIndex - this.fromIndex_1 | 0;
      }
      SubList_0.prototype.add_ydlf05_k$ = function(index, element) {
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this._size_1);
        this.list_1.add_ydlf05_k$(this.fromIndex_1 + index | 0, element);
        var tmp0_this = this;
        var tmp1 = tmp0_this._size_1;
        tmp0_this._size_1 = tmp1 + 1 | 0;
      };
      SubList_0.prototype.get_fkrdnv_k$ = function(index) {
        Companion_getInstance().checkElementIndex_ux0wz1_k$(index, this._size_1);
        return this.list_1.get_fkrdnv_k$(this.fromIndex_1 + index | 0);
      };
      SubList_0.prototype.removeAt_qvpkxi_k$ = function(index) {
        Companion_getInstance().checkElementIndex_ux0wz1_k$(index, this._size_1);
        var result = this.list_1.removeAt_qvpkxi_k$(this.fromIndex_1 + index | 0);
        var tmp0_this = this;
        var tmp1 = tmp0_this._size_1;
        tmp0_this._size_1 = tmp1 - 1 | 0;
        return result;
      };
      SubList_0.prototype.set_meu351_k$ = function(index, element) {
        Companion_getInstance().checkElementIndex_ux0wz1_k$(index, this._size_1);
        return this.list_1.set_meu351_k$(this.fromIndex_1 + index | 0, element);
      };
      SubList_0.prototype.get_size_woubt6_k$ = function() {
        return this._size_1;
      };
      SubList_0.prototype.checkIsMutable_h4zzmr_k$ = function() {
        return this.list_1.checkIsMutable_h4zzmr_k$();
      };
      SubList_0.$metadata$ = classMeta("SubList", [RandomAccess], void 0, void 0, void 0, AbstractMutableList.prototype);
      function AbstractMutableList$removeAll$lambda($elements) {
        return function(it) {
          return $elements.contains_2ehdt1_k$(it);
        };
      }
      function AbstractMutableList$retainAll$lambda($elements) {
        return function(it) {
          return !$elements.contains_2ehdt1_k$(it);
        };
      }
      function AbstractMutableList() {
        AbstractMutableCollection.call(this);
        this.modCount_1 = 0;
      }
      AbstractMutableList.prototype.set_modCount_ro74zq_k$ = function(_set____db54di) {
        this.modCount_1 = _set____db54di;
      };
      AbstractMutableList.prototype.get_modCount_sgzjli_k$ = function() {
        return this.modCount_1;
      };
      AbstractMutableList.prototype.add_1j60pz_k$ = function(element) {
        this.checkIsMutable_h4zzmr_k$();
        this.add_ydlf05_k$(this.get_size_woubt6_k$(), element);
        return true;
      };
      AbstractMutableList.prototype.addAll_ikuqlt_k$ = function(index, elements) {
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this.get_size_woubt6_k$());
        this.checkIsMutable_h4zzmr_k$();
        var _index = index;
        var changed = false;
        var tmp0_iterator = elements.iterator_jk1svi_k$();
        while (tmp0_iterator.hasNext_bitz1p_k$()) {
          var e = tmp0_iterator.next_20eer_k$();
          var tmp1 = _index;
          _index = tmp1 + 1 | 0;
          this.add_ydlf05_k$(tmp1, e);
          changed = true;
        }
        return changed;
      };
      AbstractMutableList.prototype.clear_j9y8zo_k$ = function() {
        this.checkIsMutable_h4zzmr_k$();
        this.removeRange_rbwdy0_k$(0, this.get_size_woubt6_k$());
      };
      AbstractMutableList.prototype.removeAll_99to5v_k$ = function(elements) {
        this.checkIsMutable_h4zzmr_k$();
        return removeAll(this, AbstractMutableList$removeAll$lambda(elements));
      };
      AbstractMutableList.prototype.retainAll_j44sd0_k$ = function(elements) {
        this.checkIsMutable_h4zzmr_k$();
        return removeAll(this, AbstractMutableList$retainAll$lambda(elements));
      };
      AbstractMutableList.prototype.iterator_jk1svi_k$ = function() {
        return new IteratorImpl_0(this);
      };
      AbstractMutableList.prototype.contains_2ehdt1_k$ = function(element) {
        return this.indexOf_dcv8dt_k$(element) >= 0;
      };
      AbstractMutableList.prototype.indexOf_dcv8dt_k$ = function(element) {
        var inductionVariable = 0;
        var last = get_lastIndex_6(this);
        if (inductionVariable <= last)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            if (equals(this.get_fkrdnv_k$(index), element)) {
              return index;
            }
          } while (!(index === last));
        return -1;
      };
      AbstractMutableList.prototype.lastIndexOf_rzx8t5_k$ = function(element) {
        var inductionVariable = get_lastIndex_6(this);
        if (0 <= inductionVariable)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + -1 | 0;
            if (equals(this.get_fkrdnv_k$(index), element)) {
              return index;
            }
          } while (0 <= inductionVariable);
        return -1;
      };
      AbstractMutableList.prototype.listIterator_xjshxw_k$ = function() {
        return this.listIterator_5hanv9_k$(0);
      };
      AbstractMutableList.prototype.listIterator_5hanv9_k$ = function(index) {
        return new ListIteratorImpl_0(this, index);
      };
      AbstractMutableList.prototype.subList_d153ha_k$ = function(fromIndex, toIndex) {
        return new SubList_0(this, fromIndex, toIndex);
      };
      AbstractMutableList.prototype.removeRange_rbwdy0_k$ = function(fromIndex, toIndex) {
        var iterator = this.listIterator_5hanv9_k$(fromIndex);
        var tmp0_repeat = toIndex - fromIndex | 0;
        var inductionVariable = 0;
        if (inductionVariable < tmp0_repeat)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            iterator.next_20eer_k$();
            iterator.remove_le47v1_k$();
          } while (inductionVariable < tmp0_repeat);
      };
      AbstractMutableList.prototype.equals = function(other) {
        if (other === this)
          return true;
        if (!(!(other == null) ? isInterface(other, List) : false))
          return false;
        return Companion_getInstance().orderedEquals_40uhas_k$(this, other);
      };
      AbstractMutableList.prototype.hashCode = function() {
        return Companion_getInstance().orderedHashCode_2n0xp_k$(this);
      };
      AbstractMutableList.$metadata$ = classMeta("AbstractMutableList", [MutableList], void 0, void 0, void 0, AbstractMutableCollection.prototype);
      function _set_array__c8isr0($this, _set____db54di) {
        $this.array_1 = _set____db54di;
      }
      function _get_array__jslnqg_3($this) {
        return $this.array_1;
      }
      function _set_isReadOnly__fb15ed($this, _set____db54di) {
        $this.isReadOnly_1 = _set____db54di;
      }
      function _get_isReadOnly__ud9qjl($this) {
        return $this.isReadOnly_1;
      }
      function ArrayList_init_$Init$($this) {
        var tmp$ret$0;
        tmp$ret$0 = [];
        ArrayList.call($this, tmp$ret$0);
        return $this;
      }
      function ArrayList_init_$Create$() {
        return ArrayList_init_$Init$(Object.create(ArrayList.prototype));
      }
      function ArrayList_init_$Init$_0(initialCapacity, $this) {
        var tmp$ret$0;
        tmp$ret$0 = [];
        ArrayList.call($this, tmp$ret$0);
        return $this;
      }
      function ArrayList_init_$Create$_0(initialCapacity) {
        return ArrayList_init_$Init$_0(initialCapacity, Object.create(ArrayList.prototype));
      }
      function ArrayList_init_$Init$_1(elements, $this) {
        var tmp$ret$0;
        tmp$ret$0 = copyToArray(elements);
        ArrayList.call($this, tmp$ret$0);
        return $this;
      }
      function ArrayList_init_$Create$_1(elements) {
        return ArrayList_init_$Init$_1(elements, Object.create(ArrayList.prototype));
      }
      function rangeCheck($this, index) {
        var tmp$ret$0;
        Companion_getInstance().checkElementIndex_ux0wz1_k$(index, $this.get_size_woubt6_k$());
        tmp$ret$0 = index;
        return tmp$ret$0;
      }
      function insertionRangeCheck($this, index) {
        var tmp$ret$0;
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, $this.get_size_woubt6_k$());
        tmp$ret$0 = index;
        return tmp$ret$0;
      }
      function ArrayList(array3) {
        AbstractMutableList.call(this);
        this.array_1 = array3;
        this.isReadOnly_1 = false;
      }
      ArrayList.prototype.build_1k0s4u_k$ = function() {
        this.checkIsMutable_h4zzmr_k$();
        this.isReadOnly_1 = true;
        return this;
      };
      ArrayList.prototype.trimToSize_dnhilv_k$ = function() {
      };
      ArrayList.prototype.ensureCapacity_ignus8_k$ = function(minCapacity) {
      };
      ArrayList.prototype.get_size_woubt6_k$ = function() {
        return this.array_1.length;
      };
      ArrayList.prototype.get_fkrdnv_k$ = function(index) {
        var tmp = this.array_1[rangeCheck(this, index)];
        return (tmp == null ? true : isObject3(tmp)) ? tmp : THROW_CCE();
      };
      ArrayList.prototype.set_meu351_k$ = function(index, element) {
        this.checkIsMutable_h4zzmr_k$();
        rangeCheck(this, index);
        var tmp$ret$0;
        var tmp0_apply = this.array_1[index];
        this.array_1[index] = element;
        tmp$ret$0 = tmp0_apply;
        var tmp = tmp$ret$0;
        return (tmp == null ? true : isObject3(tmp)) ? tmp : THROW_CCE();
      };
      ArrayList.prototype.add_1j60pz_k$ = function(element) {
        this.checkIsMutable_h4zzmr_k$();
        var tmp$ret$0;
        var tmp0_asDynamic = this.array_1;
        tmp$ret$0 = tmp0_asDynamic;
        tmp$ret$0.push(element);
        var tmp0_this = this;
        var tmp1 = tmp0_this.modCount_1;
        tmp0_this.modCount_1 = tmp1 + 1 | 0;
        return true;
      };
      ArrayList.prototype.add_ydlf05_k$ = function(index, element) {
        this.checkIsMutable_h4zzmr_k$();
        var tmp$ret$0;
        var tmp0_asDynamic = this.array_1;
        tmp$ret$0 = tmp0_asDynamic;
        tmp$ret$0.splice(insertionRangeCheck(this, index), 0, element);
        var tmp0_this = this;
        var tmp1 = tmp0_this.modCount_1;
        tmp0_this.modCount_1 = tmp1 + 1 | 0;
      };
      ArrayList.prototype.addAll_oxxjjk_k$ = function(elements) {
        this.checkIsMutable_h4zzmr_k$();
        if (elements.isEmpty_y1axqb_k$())
          return false;
        var tmp0_this = this;
        var tmp = tmp0_this;
        var tmp$ret$2;
        var tmp0_plus = tmp0_this.array_1;
        var tmp$ret$0;
        tmp$ret$0 = copyToArray(elements);
        var tmp1_plus = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = tmp0_plus;
        tmp$ret$2 = tmp$ret$1.concat(tmp1_plus);
        tmp.array_1 = tmp$ret$2;
        var tmp1_this = this;
        var tmp2 = tmp1_this.modCount_1;
        tmp1_this.modCount_1 = tmp2 + 1 | 0;
        return true;
      };
      ArrayList.prototype.addAll_ikuqlt_k$ = function(index, elements) {
        this.checkIsMutable_h4zzmr_k$();
        insertionRangeCheck(this, index);
        if (index === this.get_size_woubt6_k$())
          return this.addAll_oxxjjk_k$(elements);
        if (elements.isEmpty_y1axqb_k$())
          return false;
        var tmp0_subject = index;
        if (tmp0_subject === this.get_size_woubt6_k$())
          return this.addAll_oxxjjk_k$(elements);
        else if (tmp0_subject === 0) {
          var tmp = this;
          var tmp$ret$2;
          var tmp$ret$0;
          tmp$ret$0 = copyToArray(elements);
          var tmp0_plus = tmp$ret$0;
          var tmp1_plus = this.array_1;
          var tmp$ret$1;
          tmp$ret$1 = tmp0_plus;
          tmp$ret$2 = tmp$ret$1.concat(tmp1_plus);
          tmp.array_1 = tmp$ret$2;
        } else {
          var tmp_0 = this;
          var tmp$ret$3;
          var tmp2_asDynamic = copyOfRange(this.array_1, 0, index);
          tmp$ret$3 = tmp2_asDynamic;
          var tmp$ret$4;
          tmp$ret$4 = copyToArray(elements);
          tmp_0.array_1 = tmp$ret$3.concat(tmp$ret$4, copyOfRange(this.array_1, index, this.get_size_woubt6_k$()));
        }
        var tmp1_this = this;
        var tmp2 = tmp1_this.modCount_1;
        tmp1_this.modCount_1 = tmp2 + 1 | 0;
        return true;
      };
      ArrayList.prototype.removeAt_qvpkxi_k$ = function(index) {
        this.checkIsMutable_h4zzmr_k$();
        rangeCheck(this, index);
        var tmp0_this = this;
        var tmp1 = tmp0_this.modCount_1;
        tmp0_this.modCount_1 = tmp1 + 1 | 0;
        var tmp;
        if (index === get_lastIndex_6(this)) {
          var tmp$ret$0;
          var tmp0_asDynamic = this.array_1;
          tmp$ret$0 = tmp0_asDynamic;
          tmp = tmp$ret$0.pop();
        } else {
          var tmp$ret$1;
          var tmp1_asDynamic = this.array_1;
          tmp$ret$1 = tmp1_asDynamic;
          tmp = tmp$ret$1.splice(index, 1)[0];
        }
        return tmp;
      };
      ArrayList.prototype.remove_8hbkc6_k$ = function(element) {
        this.checkIsMutable_h4zzmr_k$();
        var inductionVariable = 0;
        var last = this.array_1.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            if (equals(this.array_1[index], element)) {
              var tmp$ret$0;
              var tmp0_asDynamic = this.array_1;
              tmp$ret$0 = tmp0_asDynamic;
              tmp$ret$0.splice(index, 1);
              var tmp1_this = this;
              var tmp2 = tmp1_this.modCount_1;
              tmp1_this.modCount_1 = tmp2 + 1 | 0;
              return true;
            }
          } while (inductionVariable <= last);
        return false;
      };
      ArrayList.prototype.removeRange_rbwdy0_k$ = function(fromIndex, toIndex) {
        this.checkIsMutable_h4zzmr_k$();
        var tmp0_this = this;
        var tmp1 = tmp0_this.modCount_1;
        tmp0_this.modCount_1 = tmp1 + 1 | 0;
        var tmp$ret$0;
        var tmp0_asDynamic = this.array_1;
        tmp$ret$0 = tmp0_asDynamic;
        tmp$ret$0.splice(fromIndex, toIndex - fromIndex | 0);
      };
      ArrayList.prototype.clear_j9y8zo_k$ = function() {
        this.checkIsMutable_h4zzmr_k$();
        var tmp = this;
        var tmp$ret$0;
        tmp$ret$0 = [];
        tmp.array_1 = tmp$ret$0;
        var tmp0_this = this;
        var tmp1 = tmp0_this.modCount_1;
        tmp0_this.modCount_1 = tmp1 + 1 | 0;
      };
      ArrayList.prototype.indexOf_dcv8dt_k$ = function(element) {
        return indexOf(this.array_1, element);
      };
      ArrayList.prototype.lastIndexOf_rzx8t5_k$ = function(element) {
        return lastIndexOf(this.array_1, element);
      };
      ArrayList.prototype.toString = function() {
        return arrayToString(this.array_1);
      };
      ArrayList.prototype.toArray_nu7pb_k$ = function(array3) {
        if (array3.length < this.get_size_woubt6_k$()) {
          var tmp = this.toArray_jjyjqa_k$();
          return isArray(tmp) ? tmp : THROW_CCE();
        }
        var tmp$ret$0;
        var tmp_0 = this.array_1;
        var tmp0_copyInto = isArray(tmp_0) ? tmp_0 : THROW_CCE();
        var tmp1_copyInto = tmp0_copyInto.length;
        arrayCopy(tmp0_copyInto, array3, 0, 0, tmp1_copyInto);
        tmp$ret$0 = array3;
        if (array3.length > this.get_size_woubt6_k$()) {
          var tmp_1 = this.get_size_woubt6_k$();
          array3[tmp_1] = (true ? true : isObject3(null)) ? null : THROW_CCE();
        }
        return array3;
      };
      ArrayList.prototype.toArray_jjyjqa_k$ = function() {
        return [].slice.call(this.array_1);
      };
      ArrayList.prototype.toArray = function() {
        return this.toArray_jjyjqa_k$();
      };
      ArrayList.prototype.checkIsMutable_h4zzmr_k$ = function() {
        if (this.isReadOnly_1)
          throw UnsupportedOperationException_init_$Create$();
      };
      ArrayList.$metadata$ = classMeta("ArrayList", [MutableList, RandomAccess], void 0, void 0, void 0, AbstractMutableList.prototype);
      function set__stableSortingIsSupported(_set____db54di) {
        _stableSortingIsSupported = _set____db54di;
      }
      function get__stableSortingIsSupported() {
        return _stableSortingIsSupported;
      }
      var _stableSortingIsSupported;
      function RandomAccess() {
      }
      RandomAccess.$metadata$ = interfaceMeta("RandomAccess");
      function set_output(_set____db54di) {
        init_properties_console_kt_6h8hpf();
        output = _set____db54di;
      }
      function get_output() {
        init_properties_console_kt_6h8hpf();
        return output;
      }
      var output;
      function BaseOutput() {
      }
      BaseOutput.prototype.println_uuzh5q_k$ = function() {
        this.print_o29p2b_k$("\n");
      };
      BaseOutput.prototype.println_gh3jfj_k$ = function(message) {
        this.print_o29p2b_k$(message);
        this.println_uuzh5q_k$();
      };
      BaseOutput.prototype.flush_sgqoqb_k$ = function() {
      };
      BaseOutput.$metadata$ = classMeta("BaseOutput");
      function NodeJsOutput(outputStream) {
        BaseOutput.call(this);
        this.outputStream_1 = outputStream;
      }
      NodeJsOutput.prototype.get_outputStream_2dy5nu_k$ = function() {
        return this.outputStream_1;
      };
      NodeJsOutput.prototype.print_o29p2b_k$ = function(message) {
        var tmp$ret$0;
        tmp$ret$0 = String(message);
        var messageString = tmp$ret$0;
        this.outputStream_1.write(messageString);
      };
      NodeJsOutput.$metadata$ = classMeta("NodeJsOutput", void 0, void 0, void 0, void 0, BaseOutput.prototype);
      function BufferedOutputToConsoleLog() {
        BufferedOutput.call(this);
      }
      BufferedOutputToConsoleLog.prototype.print_o29p2b_k$ = function(message) {
        var tmp$ret$0;
        tmp$ret$0 = String(message);
        var s2 = tmp$ret$0;
        var tmp$ret$2;
        var tmp0_nativeLastIndexOf = s2;
        var tmp$ret$1;
        tmp$ret$1 = tmp0_nativeLastIndexOf;
        tmp$ret$2 = tmp$ret$1.lastIndexOf("\n", 0);
        var i = tmp$ret$2;
        if (i >= 0) {
          var tmp0_this = this;
          var tmp = tmp0_this;
          var tmp_0 = tmp0_this.buffer_1;
          var tmp$ret$4;
          var tmp1_substring = s2;
          var tmp$ret$3;
          tmp$ret$3 = tmp1_substring;
          tmp$ret$4 = tmp$ret$3.substring(0, i);
          tmp.buffer_1 = tmp_0 + tmp$ret$4;
          this.flush_sgqoqb_k$();
          var tmp$ret$6;
          var tmp2_substring = s2;
          var tmp3_substring = i + 1 | 0;
          var tmp$ret$5;
          tmp$ret$5 = tmp2_substring;
          tmp$ret$6 = tmp$ret$5.substring(tmp3_substring);
          s2 = tmp$ret$6;
        }
        var tmp1_this = this;
        tmp1_this.buffer_1 = tmp1_this.buffer_1 + s2;
      };
      BufferedOutputToConsoleLog.prototype.flush_sgqoqb_k$ = function() {
        console.log(this.buffer_1);
        this.buffer_1 = "";
      };
      BufferedOutputToConsoleLog.$metadata$ = classMeta("BufferedOutputToConsoleLog", void 0, void 0, void 0, void 0, BufferedOutput.prototype);
      function String_0(value) {
        init_properties_console_kt_6h8hpf();
        return String(value);
      }
      function BufferedOutput() {
        BaseOutput.call(this);
        this.buffer_1 = "";
      }
      BufferedOutput.prototype.set_buffer_j8vbf9_k$ = function(_set____db54di) {
        this.buffer_1 = _set____db54di;
      };
      BufferedOutput.prototype.get_buffer_bmaafd_k$ = function() {
        return this.buffer_1;
      };
      BufferedOutput.prototype.print_o29p2b_k$ = function(message) {
        var tmp0_this = this;
        var tmp = tmp0_this;
        var tmp_0 = tmp0_this.buffer_1;
        var tmp$ret$0;
        tmp$ret$0 = String(message);
        tmp.buffer_1 = tmp_0 + tmp$ret$0;
      };
      BufferedOutput.prototype.flush_sgqoqb_k$ = function() {
        this.buffer_1 = "";
      };
      BufferedOutput.$metadata$ = classMeta("BufferedOutput", void 0, void 0, void 0, void 0, BaseOutput.prototype);
      function println(message) {
        init_properties_console_kt_6h8hpf();
        get_output().println_gh3jfj_k$(message);
      }
      var properties_initialized_console_kt_gll9dl;
      function init_properties_console_kt_6h8hpf() {
        if (properties_initialized_console_kt_gll9dl) {
        } else {
          properties_initialized_console_kt_gll9dl = true;
          var tmp$ret$1;
          var tmp$ret$0;
          var isNode = typeof process !== "undefined" && process.versions && !!process.versions.node;
          tmp$ret$0 = isNode ? new NodeJsOutput(process.stdout) : new BufferedOutputToConsoleLog();
          tmp$ret$1 = tmp$ret$0;
          output = tmp$ret$1;
        }
      }
      function get_EmptyContinuation() {
        init_properties_EmptyContinuation_kt_8tpm4w();
        return EmptyContinuation;
      }
      var EmptyContinuation;
      function _no_name_provided__qut3iv_0($tmp0_Continuation) {
        this.$tmp0_Continuation_1 = $tmp0_Continuation;
      }
      _no_name_provided__qut3iv_0.prototype.get_context_h02k06_k$ = function() {
        return this.$tmp0_Continuation_1;
      };
      _no_name_provided__qut3iv_0.prototype.resumeWith_7onugl_k$ = function(result) {
        var tmp$ret$0;
        throwOnFailure(result);
        var tmp = _Result___get_value__impl__bjfvqg(result);
        tmp$ret$0 = (tmp == null ? true : isObject3(tmp)) ? tmp : THROW_CCE();
        return Unit_getInstance();
      };
      _no_name_provided__qut3iv_0.prototype.resumeWith_s3a3yh_k$ = function(result) {
        return this.resumeWith_7onugl_k$(result);
      };
      _no_name_provided__qut3iv_0.$metadata$ = classMeta(void 0, [Continuation]);
      var properties_initialized_EmptyContinuation_kt_4jdb9w;
      function init_properties_EmptyContinuation_kt_8tpm4w() {
        if (properties_initialized_EmptyContinuation_kt_4jdb9w) {
        } else {
          properties_initialized_EmptyContinuation_kt_4jdb9w = true;
          var tmp$ret$0;
          var tmp0_Continuation = EmptyCoroutineContext_getInstance();
          tmp$ret$0 = new _no_name_provided__qut3iv_0(tmp0_Continuation);
          EmptyContinuation = tmp$ret$0;
        }
      }
      function asDynamic(_this__u8e3s4) {
        return _this__u8e3s4;
      }
      function unsafeCastDynamic(_this__u8e3s4) {
        return _this__u8e3s4;
      }
      function unsafeCast(_this__u8e3s4) {
        var tmp$ret$0;
        tmp$ret$0 = _this__u8e3s4;
        return tmp$ret$0;
      }
      function JsPolyfill(implementation) {
        this.implementation_1 = implementation;
      }
      JsPolyfill.prototype.get_implementation_9txf7p_k$ = function() {
        return this.implementation_1;
      };
      JsPolyfill.prototype.equals = function(other) {
        if (!(other instanceof JsPolyfill))
          return false;
        var tmp0_other_with_cast = other instanceof JsPolyfill ? other : THROW_CCE();
        if (!(this.implementation_1 === tmp0_other_with_cast.implementation_1))
          return false;
        return true;
      };
      JsPolyfill.prototype.hashCode = function() {
        return imul(getStringHashCode("implementation"), 127) ^ getStringHashCode(this.implementation_1);
      };
      JsPolyfill.prototype.toString = function() {
        return "@kotlin.js.JsPolyfill(implementation=" + this.implementation_1 + ")";
      };
      JsPolyfill.$metadata$ = classMeta("JsPolyfill", [Annotation]);
      function Serializable() {
      }
      Serializable.$metadata$ = interfaceMeta("Serializable");
      function pow(_this__u8e3s4, n2) {
        return Math.pow(_this__u8e3s4, n2);
      }
      function cos(x2) {
        return Math.cos(x2);
      }
      function min(a, b) {
        return Math.min(a, b);
      }
      function sin(x2) {
        return Math.sin(x2);
      }
      function sqrt(x2) {
        return Math.sqrt(x2);
      }
      function max(a, b) {
        return Math.max(a, b);
      }
      function abs(x2) {
        return Math.abs(x2);
      }
      function round(x2) {
        if (!(x2 % 0.5 === 0)) {
          return Math.round(x2);
        }
        var tmp$ret$0;
        tmp$ret$0 = Math.floor(x2);
        var floor2 = tmp$ret$0;
        var tmp;
        if (floor2 % 2 === 0) {
          tmp = floor2;
        } else {
          var tmp$ret$1;
          tmp$ret$1 = Math.ceil(x2);
          tmp = tmp$ret$1;
        }
        return tmp;
      }
      function roundToInt(_this__u8e3s4) {
        return roundToInt_0(_this__u8e3s4);
      }
      function floor(x2) {
        return Math.floor(x2);
      }
      function pow_0(_this__u8e3s4, x2) {
        return Math.pow(_this__u8e3s4, x2);
      }
      function atan2(y2, x2) {
        return Math.atan2(y2, x2);
      }
      function exp(x2) {
        return Math.exp(x2);
      }
      function tan(x2) {
        return Math.tan(x2);
      }
      function floor_0(x2) {
        return Math.floor(x2);
      }
      function ceil(x2) {
        return Math.ceil(x2);
      }
      function roundToInt_0(_this__u8e3s4) {
        var tmp;
        if (isNaN_0(_this__u8e3s4)) {
          throw IllegalArgumentException_init_$Create$_0("Cannot round NaN value.");
        } else if (_this__u8e3s4 > IntCompanionObject_getInstance().MAX_VALUE_1) {
          tmp = IntCompanionObject_getInstance().MAX_VALUE_1;
        } else if (_this__u8e3s4 < IntCompanionObject_getInstance().MIN_VALUE_1) {
          tmp = IntCompanionObject_getInstance().MIN_VALUE_1;
        } else {
          tmp = numberToInt(Math.round(_this__u8e3s4));
        }
        return tmp;
      }
      function nextDown(_this__u8e3s4) {
        var tmp;
        var tmp_0;
        if (isNaN_0(_this__u8e3s4)) {
          tmp_0 = true;
        } else {
          DoubleCompanionObject_getInstance();
          tmp_0 = _this__u8e3s4 === -Infinity;
        }
        if (tmp_0) {
          tmp = _this__u8e3s4;
        } else {
          if (_this__u8e3s4 === 0) {
            DoubleCompanionObject_getInstance();
            tmp = -5e-324;
          } else {
            var tmp$ret$1;
            var tmp2_fromBits = DoubleCompanionObject_getInstance();
            var tmp$ret$0;
            var tmp0_plus = toRawBits(_this__u8e3s4);
            var tmp1_plus = _this__u8e3s4 > 0 ? -1 : 1;
            tmp$ret$0 = tmp0_plus.plus_u6jwas_k$(toLong(tmp1_plus));
            var tmp3_fromBits = tmp$ret$0;
            tmp$ret$1 = doubleFromBits(tmp3_fromBits);
            tmp = tmp$ret$1;
          }
        }
        return tmp;
      }
      function isNaN_0(_this__u8e3s4) {
        return !(_this__u8e3s4 === _this__u8e3s4);
      }
      function isInfinite(_this__u8e3s4) {
        var tmp;
        DoubleCompanionObject_getInstance();
        if (_this__u8e3s4 === Infinity) {
          tmp = true;
        } else {
          DoubleCompanionObject_getInstance();
          tmp = _this__u8e3s4 === -Infinity;
        }
        return tmp;
      }
      function isFinite2(_this__u8e3s4) {
        return !isInfinite(_this__u8e3s4) ? !isNaN_0(_this__u8e3s4) : false;
      }
      function countLeadingZeroBits(_this__u8e3s4) {
        return clz32(_this__u8e3s4);
      }
      function get_INV_2_26() {
        init_properties_PlatformRandom_kt_or3gqs();
        return INV_2_26;
      }
      var INV_2_26;
      function get_INV_2_53() {
        init_properties_PlatformRandom_kt_or3gqs();
        return INV_2_53;
      }
      var INV_2_53;
      function doubleFromParts(hi26, low27) {
        init_properties_PlatformRandom_kt_or3gqs();
        return hi26 * get_INV_2_26() + low27 * get_INV_2_53();
      }
      function defaultPlatformRandom() {
        init_properties_PlatformRandom_kt_or3gqs();
        var tmp$ret$0;
        var tmp0_unsafeCast = Math.random() * Math.pow(2, 32) | 0;
        tmp$ret$0 = tmp0_unsafeCast;
        return Random_0(tmp$ret$0);
      }
      var properties_initialized_PlatformRandom_kt_uibhw8;
      function init_properties_PlatformRandom_kt_or3gqs() {
        if (properties_initialized_PlatformRandom_kt_uibhw8) {
        } else {
          properties_initialized_PlatformRandom_kt_uibhw8 = true;
          var tmp$ret$0;
          tmp$ret$0 = Math.pow(2, -26);
          INV_2_26 = tmp$ret$0;
          var tmp$ret$0_0;
          tmp$ret$0_0 = Math.pow(2, -53);
          INV_2_53 = tmp$ret$0_0;
        }
      }
      function get_js(_this__u8e3s4) {
        return (_this__u8e3s4 instanceof KClassImpl ? _this__u8e3s4 : THROW_CCE()).get_jClass_en9agn_k$();
      }
      function KCallable() {
      }
      KCallable.$metadata$ = interfaceMeta("KCallable");
      function KClass() {
      }
      KClass.$metadata$ = interfaceMeta("KClass", [KClassifier]);
      function KClassImpl(jClass) {
        this.jClass_1 = jClass;
      }
      KClassImpl.prototype.get_jClass_en9agn_k$ = function() {
        return this.jClass_1;
      };
      KClassImpl.prototype.get_qualifiedName_aokcf6_k$ = function() {
        throw NotImplementedError_init_$Create$(null, 1, null);
      };
      KClassImpl.prototype.equals = function(other) {
        var tmp;
        if (other instanceof KClassImpl) {
          tmp = equals(this.get_jClass_en9agn_k$(), other.get_jClass_en9agn_k$());
        } else {
          tmp = false;
        }
        return tmp;
      };
      KClassImpl.prototype.hashCode = function() {
        var tmp0_safe_receiver = this.get_simpleName_r6f8py_k$();
        var tmp1_elvis_lhs = tmp0_safe_receiver == null ? null : getStringHashCode(tmp0_safe_receiver);
        return tmp1_elvis_lhs == null ? 0 : tmp1_elvis_lhs;
      };
      KClassImpl.prototype.toString = function() {
        return "class " + this.get_simpleName_r6f8py_k$();
      };
      KClassImpl.$metadata$ = classMeta("KClassImpl", [KClass]);
      function _get_givenSimpleName__jpleuh($this) {
        return $this.givenSimpleName_1;
      }
      function _get_isInstanceFunction__fkefl8($this) {
        return $this.isInstanceFunction_1;
      }
      function PrimitiveKClassImpl(jClass, givenSimpleName, isInstanceFunction) {
        KClassImpl.call(this, jClass);
        this.givenSimpleName_1 = givenSimpleName;
        this.isInstanceFunction_1 = isInstanceFunction;
      }
      PrimitiveKClassImpl.prototype.equals = function(other) {
        if (!(other instanceof PrimitiveKClassImpl))
          return false;
        return KClassImpl.prototype.equals.call(this, other) ? this.givenSimpleName_1 === other.givenSimpleName_1 : false;
      };
      PrimitiveKClassImpl.prototype.get_simpleName_r6f8py_k$ = function() {
        return this.givenSimpleName_1;
      };
      PrimitiveKClassImpl.prototype.isInstance_6tn68w_k$ = function(value) {
        return this.isInstanceFunction_1(value);
      };
      PrimitiveKClassImpl.$metadata$ = classMeta("PrimitiveKClassImpl", void 0, void 0, void 0, void 0, KClassImpl.prototype);
      function NothingKClassImpl() {
        NothingKClassImpl_instance = this;
        KClassImpl.call(this, Object);
        this.simpleName_1 = "Nothing";
      }
      NothingKClassImpl.prototype.get_simpleName_r6f8py_k$ = function() {
        return this.simpleName_1;
      };
      NothingKClassImpl.prototype.isInstance_6tn68w_k$ = function(value) {
        return false;
      };
      NothingKClassImpl.prototype.get_jClass_en9agn_k$ = function() {
        throw UnsupportedOperationException_init_$Create$_0("There's no native JS class for Nothing type");
      };
      NothingKClassImpl.prototype.equals = function(other) {
        return other === this;
      };
      NothingKClassImpl.prototype.hashCode = function() {
        return 0;
      };
      NothingKClassImpl.$metadata$ = objectMeta("NothingKClassImpl", void 0, void 0, void 0, void 0, KClassImpl.prototype);
      var NothingKClassImpl_instance;
      function NothingKClassImpl_getInstance() {
        if (NothingKClassImpl_instance == null)
          new NothingKClassImpl();
        return NothingKClassImpl_instance;
      }
      function ErrorKClass() {
      }
      ErrorKClass.prototype.get_simpleName_r6f8py_k$ = function() {
        throw IllegalStateException_init_$Create$_0("Unknown simpleName for ErrorKClass");
      };
      ErrorKClass.prototype.get_qualifiedName_aokcf6_k$ = function() {
        throw IllegalStateException_init_$Create$_0("Unknown qualifiedName for ErrorKClass");
      };
      ErrorKClass.prototype.isInstance_6tn68w_k$ = function(value) {
        throw IllegalStateException_init_$Create$_0("Can's check isInstance on ErrorKClass");
      };
      ErrorKClass.prototype.equals = function(other) {
        return other === this;
      };
      ErrorKClass.prototype.hashCode = function() {
        return 0;
      };
      ErrorKClass.$metadata$ = classMeta("ErrorKClass", [KClass]);
      function SimpleKClassImpl(jClass) {
        KClassImpl.call(this, jClass);
        var tmp = this;
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = jClass;
        var tmp0_safe_receiver = tmp$ret$0.$metadata$;
        var tmp0_unsafeCast = tmp0_safe_receiver == null ? null : tmp0_safe_receiver.simpleName;
        tmp$ret$1 = tmp0_unsafeCast;
        tmp.simpleName_1 = tmp$ret$1;
      }
      SimpleKClassImpl.prototype.get_simpleName_r6f8py_k$ = function() {
        return this.simpleName_1;
      };
      SimpleKClassImpl.prototype.isInstance_6tn68w_k$ = function(value) {
        return jsIsType(value, this.get_jClass_en9agn_k$());
      };
      SimpleKClassImpl.$metadata$ = classMeta("SimpleKClassImpl", void 0, void 0, void 0, void 0, KClassImpl.prototype);
      function KFunction() {
      }
      KFunction.$metadata$ = interfaceMeta("KFunction", [KCallable]);
      function KProperty() {
      }
      KProperty.$metadata$ = interfaceMeta("KProperty", [KCallable]);
      function KProperty0() {
      }
      KProperty0.$metadata$ = interfaceMeta("KProperty0", [KProperty]);
      function KProperty1() {
      }
      KProperty1.$metadata$ = interfaceMeta("KProperty1", [KProperty]);
      function KProperty2() {
      }
      KProperty2.$metadata$ = interfaceMeta("KProperty2", [KProperty]);
      function KMutableProperty0() {
      }
      KMutableProperty0.$metadata$ = interfaceMeta("KMutableProperty0", [KProperty0, KMutableProperty]);
      function KMutableProperty() {
      }
      KMutableProperty.$metadata$ = interfaceMeta("KMutableProperty", [KProperty]);
      function KMutableProperty1() {
      }
      KMutableProperty1.$metadata$ = interfaceMeta("KMutableProperty1", [KProperty1, KMutableProperty]);
      function KMutableProperty2() {
      }
      KMutableProperty2.$metadata$ = interfaceMeta("KMutableProperty2", [KProperty2, KMutableProperty]);
      function KType() {
      }
      KType.$metadata$ = interfaceMeta("KType");
      function createKType(classifier, arguments_0, isMarkedNullable) {
        return new KTypeImpl(classifier, asList(arguments_0), isMarkedNullable);
      }
      function createDynamicKType() {
        return DynamicKType_getInstance();
      }
      function createKTypeParameter(name, upperBounds, variance) {
        var tmp0_subject = variance;
        {
          var kVariance;
          switch (tmp0_subject) {
            case "in":
              kVariance = KVariance_IN_getInstance();
              break;
            case "out":
              kVariance = KVariance_OUT_getInstance();
              break;
            default:
              kVariance = KVariance_INVARIANT_getInstance();
              break;
          }
        }
        return new KTypeParameterImpl(name, asList(upperBounds), kVariance, false);
      }
      function getStarKTypeProjection() {
        return Companion_getInstance_8().get_STAR_wo9fa3_k$();
      }
      function createCovariantKTypeProjection(type) {
        return Companion_getInstance_8().covariant_ne14kt_k$(type);
      }
      function createInvariantKTypeProjection(type) {
        return Companion_getInstance_8().invariant_d1std2_k$(type);
      }
      function createContravariantKTypeProjection(type) {
        return Companion_getInstance_8().contravariant_lnygde_k$(type);
      }
      function KTypeImpl(classifier, arguments_0, isMarkedNullable) {
        this.classifier_1 = classifier;
        this.arguments_1 = arguments_0;
        this.isMarkedNullable_1 = isMarkedNullable;
      }
      KTypeImpl.prototype.get_classifier_ottyl2_k$ = function() {
        return this.classifier_1;
      };
      KTypeImpl.prototype.get_arguments_p5ddub_k$ = function() {
        return this.arguments_1;
      };
      KTypeImpl.prototype.get_isMarkedNullable_4el8ow_k$ = function() {
        return this.isMarkedNullable_1;
      };
      KTypeImpl.prototype.equals = function(other) {
        var tmp;
        var tmp_0;
        var tmp_1;
        if (other instanceof KTypeImpl) {
          tmp_1 = equals(this.classifier_1, other.classifier_1);
        } else {
          tmp_1 = false;
        }
        if (tmp_1) {
          tmp_0 = equals(this.arguments_1, other.arguments_1);
        } else {
          tmp_0 = false;
        }
        if (tmp_0) {
          tmp = this.isMarkedNullable_1 === other.isMarkedNullable_1;
        } else {
          tmp = false;
        }
        return tmp;
      };
      KTypeImpl.prototype.hashCode = function() {
        return imul(imul(hashCode(this.classifier_1), 31) + hashCode(this.arguments_1) | 0, 31) + (this.isMarkedNullable_1 | 0) | 0;
      };
      KTypeImpl.prototype.toString = function() {
        var tmp = this.classifier_1;
        var kClass = isInterface(tmp, KClass) ? tmp : null;
        var classifierName = kClass == null ? toString_1(this.classifier_1) : !(kClass.get_simpleName_r6f8py_k$() == null) ? kClass.get_simpleName_r6f8py_k$() : "(non-denotable type)";
        var tmp_0;
        if (this.arguments_1.isEmpty_y1axqb_k$()) {
          tmp_0 = "";
        } else {
          tmp_0 = joinToString$default_0(this.arguments_1, ", ", "<", ">", 0, null, null, 56, null);
        }
        var args = tmp_0;
        var nullable2 = this.isMarkedNullable_1 ? "?" : "";
        return plus_0(classifierName, args) + nullable2;
      };
      KTypeImpl.$metadata$ = classMeta("KTypeImpl", [KType]);
      function DynamicKType() {
        DynamicKType_instance = this;
        this.classifier_1 = null;
        this.arguments_1 = emptyList();
        this.isMarkedNullable_1 = false;
      }
      DynamicKType.prototype.get_classifier_ottyl2_k$ = function() {
        return this.classifier_1;
      };
      DynamicKType.prototype.get_arguments_p5ddub_k$ = function() {
        return this.arguments_1;
      };
      DynamicKType.prototype.get_isMarkedNullable_4el8ow_k$ = function() {
        return this.isMarkedNullable_1;
      };
      DynamicKType.prototype.toString = function() {
        return "dynamic";
      };
      DynamicKType.$metadata$ = objectMeta("DynamicKType", [KType]);
      var DynamicKType_instance;
      function DynamicKType_getInstance() {
        if (DynamicKType_instance == null)
          new DynamicKType();
        return DynamicKType_instance;
      }
      function KTypeParameterImpl(name, upperBounds, variance, isReified) {
        this.name_1 = name;
        this.upperBounds_1 = upperBounds;
        this.variance_1 = variance;
        this.isReified_1 = isReified;
      }
      KTypeParameterImpl.prototype.get_name_woqyms_k$ = function() {
        return this.name_1;
      };
      KTypeParameterImpl.prototype.get_upperBounds_k5qia_k$ = function() {
        return this.upperBounds_1;
      };
      KTypeParameterImpl.prototype.get_variance_ik7ku2_k$ = function() {
        return this.variance_1;
      };
      KTypeParameterImpl.prototype.get_isReified_gx0s91_k$ = function() {
        return this.isReified_1;
      };
      KTypeParameterImpl.prototype.toString = function() {
        return this.name_1;
      };
      KTypeParameterImpl.prototype.component1_7eebsc_k$ = function() {
        return this.name_1;
      };
      KTypeParameterImpl.prototype.component2_7eebsb_k$ = function() {
        return this.upperBounds_1;
      };
      KTypeParameterImpl.prototype.component3_7eebsa_k$ = function() {
        return this.variance_1;
      };
      KTypeParameterImpl.prototype.component4_7eebs9_k$ = function() {
        return this.isReified_1;
      };
      KTypeParameterImpl.prototype.copy_21tpu9_k$ = function(name, upperBounds, variance, isReified) {
        return new KTypeParameterImpl(name, upperBounds, variance, isReified);
      };
      KTypeParameterImpl.prototype.copy$default_6ckzz_k$ = function(name, upperBounds, variance, isReified, $mask0, $handler) {
        if (!(($mask0 & 1) === 0))
          name = this.name_1;
        if (!(($mask0 & 2) === 0))
          upperBounds = this.upperBounds_1;
        if (!(($mask0 & 4) === 0))
          variance = this.variance_1;
        if (!(($mask0 & 8) === 0))
          isReified = this.isReified_1;
        return this.copy_21tpu9_k$(name, upperBounds, variance, isReified);
      };
      KTypeParameterImpl.prototype.hashCode = function() {
        var result = getStringHashCode(this.name_1);
        result = imul(result, 31) + hashCode(this.upperBounds_1) | 0;
        result = imul(result, 31) + this.variance_1.hashCode() | 0;
        result = imul(result, 31) + (this.isReified_1 | 0) | 0;
        return result;
      };
      KTypeParameterImpl.prototype.equals = function(other) {
        if (this === other)
          return true;
        if (!(other instanceof KTypeParameterImpl))
          return false;
        var tmp0_other_with_cast = other instanceof KTypeParameterImpl ? other : THROW_CCE();
        if (!(this.name_1 === tmp0_other_with_cast.name_1))
          return false;
        if (!equals(this.upperBounds_1, tmp0_other_with_cast.upperBounds_1))
          return false;
        if (!this.variance_1.equals(tmp0_other_with_cast.variance_1))
          return false;
        if (!(this.isReified_1 === tmp0_other_with_cast.isReified_1))
          return false;
        return true;
      };
      KTypeParameterImpl.$metadata$ = classMeta("KTypeParameterImpl", [KTypeParameter]);
      function get_functionClasses() {
        init_properties_primitives_kt_rm1w5q();
        return functionClasses;
      }
      var functionClasses;
      function PrimitiveClasses$anyClass$lambda(it) {
        return isObject3(it);
      }
      function PrimitiveClasses$numberClass$lambda(it) {
        return isNumber2(it);
      }
      function PrimitiveClasses$booleanClass$lambda(it) {
        return !(it == null) ? typeof it === "boolean" : false;
      }
      function PrimitiveClasses$byteClass$lambda(it) {
        return !(it == null) ? typeof it === "number" : false;
      }
      function PrimitiveClasses$shortClass$lambda(it) {
        return !(it == null) ? typeof it === "number" : false;
      }
      function PrimitiveClasses$intClass$lambda(it) {
        return !(it == null) ? typeof it === "number" : false;
      }
      function PrimitiveClasses$floatClass$lambda(it) {
        return !(it == null) ? typeof it === "number" : false;
      }
      function PrimitiveClasses$doubleClass$lambda(it) {
        return !(it == null) ? typeof it === "number" : false;
      }
      function PrimitiveClasses$arrayClass$lambda(it) {
        return !(it == null) ? isArray(it) : false;
      }
      function PrimitiveClasses$stringClass$lambda(it) {
        return !(it == null) ? typeof it === "string" : false;
      }
      function PrimitiveClasses$throwableClass$lambda(it) {
        return it instanceof Error;
      }
      function PrimitiveClasses$booleanArrayClass$lambda(it) {
        return !(it == null) ? isBooleanArray(it) : false;
      }
      function PrimitiveClasses$charArrayClass$lambda(it) {
        return !(it == null) ? isCharArray(it) : false;
      }
      function PrimitiveClasses$byteArrayClass$lambda(it) {
        return !(it == null) ? isByteArray(it) : false;
      }
      function PrimitiveClasses$shortArrayClass$lambda(it) {
        return !(it == null) ? isShortArray(it) : false;
      }
      function PrimitiveClasses$intArrayClass$lambda(it) {
        return !(it == null) ? isIntArray(it) : false;
      }
      function PrimitiveClasses$longArrayClass$lambda(it) {
        return !(it == null) ? isLongArray(it) : false;
      }
      function PrimitiveClasses$floatArrayClass$lambda(it) {
        return !(it == null) ? isFloatArray(it) : false;
      }
      function PrimitiveClasses$doubleArrayClass$lambda(it) {
        return !(it == null) ? isDoubleArray(it) : false;
      }
      function PrimitiveClasses$functionClass$lambda($arity) {
        return function(it) {
          var tmp;
          if (typeof it === "function") {
            var tmp$ret$0;
            tmp$ret$0 = it;
            tmp = tmp$ret$0.length === $arity;
          } else {
            tmp = false;
          }
          return tmp;
        };
      }
      function PrimitiveClasses() {
        PrimitiveClasses_instance = this;
        var tmp = this;
        var tmp$ret$0;
        var tmp0_unsafeCast = Object;
        tmp$ret$0 = tmp0_unsafeCast;
        var tmp_0 = tmp$ret$0;
        tmp.anyClass_1 = new PrimitiveKClassImpl(tmp_0, "Any", PrimitiveClasses$anyClass$lambda);
        var tmp_1 = this;
        var tmp$ret$1;
        var tmp0_unsafeCast_0 = Number;
        tmp$ret$1 = tmp0_unsafeCast_0;
        var tmp_2 = tmp$ret$1;
        tmp_1.numberClass_1 = new PrimitiveKClassImpl(tmp_2, "Number", PrimitiveClasses$numberClass$lambda);
        this.nothingClass_1 = NothingKClassImpl_getInstance();
        var tmp_3 = this;
        var tmp$ret$2;
        var tmp0_unsafeCast_1 = Boolean;
        tmp$ret$2 = tmp0_unsafeCast_1;
        var tmp_4 = tmp$ret$2;
        tmp_3.booleanClass_1 = new PrimitiveKClassImpl(tmp_4, "Boolean", PrimitiveClasses$booleanClass$lambda);
        var tmp_5 = this;
        var tmp$ret$3;
        var tmp0_unsafeCast_2 = Number;
        tmp$ret$3 = tmp0_unsafeCast_2;
        var tmp_6 = tmp$ret$3;
        tmp_5.byteClass_1 = new PrimitiveKClassImpl(tmp_6, "Byte", PrimitiveClasses$byteClass$lambda);
        var tmp_7 = this;
        var tmp$ret$4;
        var tmp0_unsafeCast_3 = Number;
        tmp$ret$4 = tmp0_unsafeCast_3;
        var tmp_8 = tmp$ret$4;
        tmp_7.shortClass_1 = new PrimitiveKClassImpl(tmp_8, "Short", PrimitiveClasses$shortClass$lambda);
        var tmp_9 = this;
        var tmp$ret$5;
        var tmp0_unsafeCast_4 = Number;
        tmp$ret$5 = tmp0_unsafeCast_4;
        var tmp_10 = tmp$ret$5;
        tmp_9.intClass_1 = new PrimitiveKClassImpl(tmp_10, "Int", PrimitiveClasses$intClass$lambda);
        var tmp_11 = this;
        var tmp$ret$6;
        var tmp0_unsafeCast_5 = Number;
        tmp$ret$6 = tmp0_unsafeCast_5;
        var tmp_12 = tmp$ret$6;
        tmp_11.floatClass_1 = new PrimitiveKClassImpl(tmp_12, "Float", PrimitiveClasses$floatClass$lambda);
        var tmp_13 = this;
        var tmp$ret$7;
        var tmp0_unsafeCast_6 = Number;
        tmp$ret$7 = tmp0_unsafeCast_6;
        var tmp_14 = tmp$ret$7;
        tmp_13.doubleClass_1 = new PrimitiveKClassImpl(tmp_14, "Double", PrimitiveClasses$doubleClass$lambda);
        var tmp_15 = this;
        var tmp$ret$8;
        var tmp0_unsafeCast_7 = Array;
        tmp$ret$8 = tmp0_unsafeCast_7;
        var tmp_16 = tmp$ret$8;
        tmp_15.arrayClass_1 = new PrimitiveKClassImpl(tmp_16, "Array", PrimitiveClasses$arrayClass$lambda);
        var tmp_17 = this;
        var tmp$ret$9;
        var tmp0_unsafeCast_8 = String;
        tmp$ret$9 = tmp0_unsafeCast_8;
        var tmp_18 = tmp$ret$9;
        tmp_17.stringClass_1 = new PrimitiveKClassImpl(tmp_18, "String", PrimitiveClasses$stringClass$lambda);
        var tmp_19 = this;
        var tmp$ret$10;
        var tmp0_unsafeCast_9 = Error;
        tmp$ret$10 = tmp0_unsafeCast_9;
        var tmp_20 = tmp$ret$10;
        tmp_19.throwableClass_1 = new PrimitiveKClassImpl(tmp_20, "Throwable", PrimitiveClasses$throwableClass$lambda);
        var tmp_21 = this;
        var tmp$ret$11;
        var tmp0_unsafeCast_10 = Array;
        tmp$ret$11 = tmp0_unsafeCast_10;
        var tmp_22 = tmp$ret$11;
        tmp_21.booleanArrayClass_1 = new PrimitiveKClassImpl(tmp_22, "BooleanArray", PrimitiveClasses$booleanArrayClass$lambda);
        var tmp_23 = this;
        var tmp$ret$12;
        var tmp0_unsafeCast_11 = Uint16Array;
        tmp$ret$12 = tmp0_unsafeCast_11;
        var tmp_24 = tmp$ret$12;
        tmp_23.charArrayClass_1 = new PrimitiveKClassImpl(tmp_24, "CharArray", PrimitiveClasses$charArrayClass$lambda);
        var tmp_25 = this;
        var tmp$ret$13;
        var tmp0_unsafeCast_12 = Int8Array;
        tmp$ret$13 = tmp0_unsafeCast_12;
        var tmp_26 = tmp$ret$13;
        tmp_25.byteArrayClass_1 = new PrimitiveKClassImpl(tmp_26, "ByteArray", PrimitiveClasses$byteArrayClass$lambda);
        var tmp_27 = this;
        var tmp$ret$14;
        var tmp0_unsafeCast_13 = Int16Array;
        tmp$ret$14 = tmp0_unsafeCast_13;
        var tmp_28 = tmp$ret$14;
        tmp_27.shortArrayClass_1 = new PrimitiveKClassImpl(tmp_28, "ShortArray", PrimitiveClasses$shortArrayClass$lambda);
        var tmp_29 = this;
        var tmp$ret$15;
        var tmp0_unsafeCast_14 = Int32Array;
        tmp$ret$15 = tmp0_unsafeCast_14;
        var tmp_30 = tmp$ret$15;
        tmp_29.intArrayClass_1 = new PrimitiveKClassImpl(tmp_30, "IntArray", PrimitiveClasses$intArrayClass$lambda);
        var tmp_31 = this;
        var tmp$ret$16;
        var tmp0_unsafeCast_15 = Array;
        tmp$ret$16 = tmp0_unsafeCast_15;
        var tmp_32 = tmp$ret$16;
        tmp_31.longArrayClass_1 = new PrimitiveKClassImpl(tmp_32, "LongArray", PrimitiveClasses$longArrayClass$lambda);
        var tmp_33 = this;
        var tmp$ret$17;
        var tmp0_unsafeCast_16 = Float32Array;
        tmp$ret$17 = tmp0_unsafeCast_16;
        var tmp_34 = tmp$ret$17;
        tmp_33.floatArrayClass_1 = new PrimitiveKClassImpl(tmp_34, "FloatArray", PrimitiveClasses$floatArrayClass$lambda);
        var tmp_35 = this;
        var tmp$ret$18;
        var tmp0_unsafeCast_17 = Float64Array;
        tmp$ret$18 = tmp0_unsafeCast_17;
        var tmp_36 = tmp$ret$18;
        tmp_35.doubleArrayClass_1 = new PrimitiveKClassImpl(tmp_36, "DoubleArray", PrimitiveClasses$doubleArrayClass$lambda);
      }
      PrimitiveClasses.prototype.get_anyClass_x0jl4l_k$ = function() {
        return this.anyClass_1;
      };
      PrimitiveClasses.prototype.get_numberClass_pnym9y_k$ = function() {
        return this.numberClass_1;
      };
      PrimitiveClasses.prototype.get_nothingClass_7ivpcc_k$ = function() {
        return this.nothingClass_1;
      };
      PrimitiveClasses.prototype.get_booleanClass_d285fr_k$ = function() {
        return this.booleanClass_1;
      };
      PrimitiveClasses.prototype.get_byteClass_pu7s61_k$ = function() {
        return this.byteClass_1;
      };
      PrimitiveClasses.prototype.get_shortClass_5ajsv9_k$ = function() {
        return this.shortClass_1;
      };
      PrimitiveClasses.prototype.get_intClass_mw4y9a_k$ = function() {
        return this.intClass_1;
      };
      PrimitiveClasses.prototype.get_floatClass_xlwq2t_k$ = function() {
        return this.floatClass_1;
      };
      PrimitiveClasses.prototype.get_doubleClass_dahzcy_k$ = function() {
        return this.doubleClass_1;
      };
      PrimitiveClasses.prototype.get_arrayClass_udg0fc_k$ = function() {
        return this.arrayClass_1;
      };
      PrimitiveClasses.prototype.get_stringClass_bik2gy_k$ = function() {
        return this.stringClass_1;
      };
      PrimitiveClasses.prototype.get_throwableClass_ee1a8x_k$ = function() {
        return this.throwableClass_1;
      };
      PrimitiveClasses.prototype.get_booleanArrayClass_lnbwea_k$ = function() {
        return this.booleanArrayClass_1;
      };
      PrimitiveClasses.prototype.get_charArrayClass_7lhfoe_k$ = function() {
        return this.charArrayClass_1;
      };
      PrimitiveClasses.prototype.get_byteArrayClass_57my8g_k$ = function() {
        return this.byteArrayClass_1;
      };
      PrimitiveClasses.prototype.get_shortArrayClass_c1p7wy_k$ = function() {
        return this.shortArrayClass_1;
      };
      PrimitiveClasses.prototype.get_intArrayClass_h44pbv_k$ = function() {
        return this.intArrayClass_1;
      };
      PrimitiveClasses.prototype.get_longArrayClass_v379a4_k$ = function() {
        return this.longArrayClass_1;
      };
      PrimitiveClasses.prototype.get_floatArrayClass_qngmha_k$ = function() {
        return this.floatArrayClass_1;
      };
      PrimitiveClasses.prototype.get_doubleArrayClass_84hee1_k$ = function() {
        return this.doubleArrayClass_1;
      };
      PrimitiveClasses.prototype.functionClass = function(arity) {
        var tmp0_elvis_lhs = get_functionClasses()[arity];
        var tmp;
        if (tmp0_elvis_lhs == null) {
          var tmp$ret$3;
          var tmp$ret$2;
          var tmp$ret$0;
          var tmp0_unsafeCast = Function;
          tmp$ret$0 = tmp0_unsafeCast;
          var tmp_0 = tmp$ret$0;
          var tmp_1 = "Function" + arity;
          var result = new PrimitiveKClassImpl(tmp_0, tmp_1, PrimitiveClasses$functionClass$lambda(arity));
          var tmp$ret$1;
          var tmp1_asDynamic = get_functionClasses();
          tmp$ret$1 = tmp1_asDynamic;
          tmp$ret$1[arity] = result;
          tmp$ret$2 = result;
          tmp$ret$3 = tmp$ret$2;
          tmp = tmp$ret$3;
        } else {
          tmp = tmp0_elvis_lhs;
        }
        return tmp;
      };
      PrimitiveClasses.$metadata$ = objectMeta("PrimitiveClasses");
      Object.defineProperty(PrimitiveClasses.prototype, "anyClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_anyClass_x0jl4l_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "numberClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_numberClass_pnym9y_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "nothingClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_nothingClass_7ivpcc_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "booleanClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_booleanClass_d285fr_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "byteClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_byteClass_pu7s61_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "shortClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_shortClass_5ajsv9_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "intClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_intClass_mw4y9a_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "floatClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_floatClass_xlwq2t_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "doubleClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_doubleClass_dahzcy_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "arrayClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_arrayClass_udg0fc_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "stringClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_stringClass_bik2gy_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "throwableClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_throwableClass_ee1a8x_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "booleanArrayClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_booleanArrayClass_lnbwea_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "charArrayClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_charArrayClass_7lhfoe_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "byteArrayClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_byteArrayClass_57my8g_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "shortArrayClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_shortArrayClass_c1p7wy_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "intArrayClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_intArrayClass_h44pbv_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "longArrayClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_longArrayClass_v379a4_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "floatArrayClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_floatArrayClass_qngmha_k$
      });
      Object.defineProperty(PrimitiveClasses.prototype, "doubleArrayClass", {
        configurable: true,
        get: PrimitiveClasses.prototype.get_doubleArrayClass_84hee1_k$
      });
      var PrimitiveClasses_instance;
      function PrimitiveClasses_getInstance() {
        if (PrimitiveClasses_instance == null)
          new PrimitiveClasses();
        return PrimitiveClasses_instance;
      }
      var properties_initialized_primitives_kt_jle18u;
      function init_properties_primitives_kt_rm1w5q() {
        if (properties_initialized_primitives_kt_jle18u) {
        } else {
          properties_initialized_primitives_kt_jle18u = true;
          var tmp$ret$0;
          tmp$ret$0 = fillArrayVal(Array(0), null);
          functionClasses = tmp$ret$0;
        }
      }
      function getKClass(jClass) {
        var tmp;
        if (Array.isArray(jClass)) {
          var tmp$ret$1;
          var tmp$ret$0;
          tmp$ret$0 = jClass;
          tmp$ret$1 = tmp$ret$0;
          tmp = getKClassM(tmp$ret$1);
        } else {
          var tmp$ret$3;
          var tmp$ret$2;
          tmp$ret$2 = jClass;
          tmp$ret$3 = tmp$ret$2;
          tmp = getKClass1(tmp$ret$3);
        }
        return tmp;
      }
      function getKClassM(jClasses) {
        var tmp0_subject = jClasses.length;
        var tmp;
        switch (tmp0_subject) {
          case 1:
            tmp = getKClass1(jClasses[0]);
            break;
          case 0:
            var tmp$ret$1;
            var tmp0_unsafeCast = NothingKClassImpl_getInstance();
            var tmp$ret$0;
            tmp$ret$0 = tmp0_unsafeCast;
            tmp$ret$1 = tmp$ret$0;
            tmp = tmp$ret$1;
            break;
          default:
            var tmp$ret$3;
            var tmp1_unsafeCast = new ErrorKClass();
            var tmp$ret$2;
            tmp$ret$2 = tmp1_unsafeCast;
            tmp$ret$3 = tmp$ret$2;
            tmp = tmp$ret$3;
            break;
        }
        return tmp;
      }
      function getKClass1(jClass) {
        if (jClass === String) {
          var tmp$ret$1;
          var tmp0_unsafeCast = PrimitiveClasses_getInstance().stringClass_1;
          var tmp$ret$0;
          tmp$ret$0 = tmp0_unsafeCast;
          tmp$ret$1 = tmp$ret$0;
          return tmp$ret$1;
        }
        var tmp$ret$2;
        tmp$ret$2 = jClass;
        var metadata = tmp$ret$2.$metadata$;
        var tmp;
        if (metadata != null) {
          var tmp_0;
          if (metadata.$kClass$ == null) {
            var kClass = new SimpleKClassImpl(jClass);
            metadata.$kClass$ = kClass;
            tmp_0 = kClass;
          } else {
            tmp_0 = metadata.$kClass$;
          }
          tmp = tmp_0;
        } else {
          tmp = new SimpleKClassImpl(jClass);
        }
        return tmp;
      }
      function getKClassFromExpression(e) {
        var tmp$ret$3;
        var tmp0_subject = typeof e;
        var tmp;
        switch (tmp0_subject) {
          case "string":
            tmp = PrimitiveClasses_getInstance().stringClass_1;
            break;
          case "number":
            var tmp_0;
            var tmp$ret$0;
            var tmp0_asDynamic = jsBitwiseOr(e, 0);
            tmp$ret$0 = tmp0_asDynamic;
            if (tmp$ret$0 === e) {
              tmp_0 = PrimitiveClasses_getInstance().intClass_1;
            } else {
              tmp_0 = PrimitiveClasses_getInstance().doubleClass_1;
            }
            tmp = tmp_0;
            break;
          case "boolean":
            tmp = PrimitiveClasses_getInstance().booleanClass_1;
            break;
          case "function":
            var tmp_1 = PrimitiveClasses_getInstance();
            var tmp$ret$1;
            tmp$ret$1 = e;
            tmp = tmp_1.functionClass(tmp$ret$1.length);
            break;
          default:
            var tmp_2;
            if (isBooleanArray(e)) {
              tmp_2 = PrimitiveClasses_getInstance().booleanArrayClass_1;
            } else {
              if (isCharArray(e)) {
                tmp_2 = PrimitiveClasses_getInstance().charArrayClass_1;
              } else {
                if (isByteArray(e)) {
                  tmp_2 = PrimitiveClasses_getInstance().byteArrayClass_1;
                } else {
                  if (isShortArray(e)) {
                    tmp_2 = PrimitiveClasses_getInstance().shortArrayClass_1;
                  } else {
                    if (isIntArray(e)) {
                      tmp_2 = PrimitiveClasses_getInstance().intArrayClass_1;
                    } else {
                      if (isLongArray(e)) {
                        tmp_2 = PrimitiveClasses_getInstance().longArrayClass_1;
                      } else {
                        if (isFloatArray(e)) {
                          tmp_2 = PrimitiveClasses_getInstance().floatArrayClass_1;
                        } else {
                          if (isDoubleArray(e)) {
                            tmp_2 = PrimitiveClasses_getInstance().doubleArrayClass_1;
                          } else {
                            if (isInterface(e, KClass)) {
                              tmp_2 = getKClass(KClass);
                            } else {
                              if (isArray(e)) {
                                tmp_2 = PrimitiveClasses_getInstance().arrayClass_1;
                              } else {
                                var constructor = Object.getPrototypeOf(e).constructor;
                                var tmp_3;
                                if (constructor === Object) {
                                  tmp_3 = PrimitiveClasses_getInstance().anyClass_1;
                                } else if (constructor === Error) {
                                  tmp_3 = PrimitiveClasses_getInstance().throwableClass_1;
                                } else {
                                  var jsClass = constructor;
                                  tmp_3 = getKClass1(jsClass);
                                }
                                tmp_2 = tmp_3;
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
            tmp = tmp_2;
            break;
        }
        var tmp1_unsafeCast = tmp;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_unsafeCast;
        tmp$ret$3 = tmp$ret$2;
        return tmp$ret$3;
      }
      function Appendable() {
      }
      Appendable.$metadata$ = interfaceMeta("Appendable");
      function StringBuilder_init_$Init$(capacity, $this) {
        StringBuilder_init_$Init$_1($this);
        return $this;
      }
      function StringBuilder_init_$Create$(capacity) {
        return StringBuilder_init_$Init$(capacity, Object.create(StringBuilder.prototype));
      }
      function StringBuilder_init_$Init$_0(content, $this) {
        StringBuilder.call($this, toString_1(content));
        return $this;
      }
      function StringBuilder_init_$Create$_0(content) {
        return StringBuilder_init_$Init$_0(content, Object.create(StringBuilder.prototype));
      }
      function StringBuilder_init_$Init$_1($this) {
        StringBuilder.call($this, "");
        return $this;
      }
      function StringBuilder_init_$Create$_1() {
        return StringBuilder_init_$Init$_1(Object.create(StringBuilder.prototype));
      }
      function _set_string__57jj1i($this, _set____db54di) {
        $this.string_1 = _set____db54di;
      }
      function _get_string__6oa3oa($this) {
        return $this.string_1;
      }
      function checkReplaceRange($this, startIndex, endIndex, length) {
        if (startIndex < 0 ? true : startIndex > length) {
          throw IndexOutOfBoundsException_init_$Create$_0("startIndex: " + startIndex + ", length: " + length);
        }
        if (startIndex > endIndex) {
          throw IllegalArgumentException_init_$Create$_0("startIndex(" + startIndex + ") > endIndex(" + endIndex + ")");
        }
      }
      function StringBuilder(content) {
        this.string_1 = !(content === void 0) ? content : "";
      }
      StringBuilder.prototype.get_length_g42xv3_k$ = function() {
        var tmp$ret$0;
        var tmp0_asDynamic = this.string_1;
        tmp$ret$0 = tmp0_asDynamic;
        return tmp$ret$0.length;
      };
      StringBuilder.prototype.get_a7b70_k$ = function(index) {
        var tmp$ret$0;
        var tmp0_getOrElse = this.string_1;
        var tmp;
        if (index >= 0 ? index <= get_lastIndex_7(tmp0_getOrElse) : false) {
          tmp = charSequenceGet(tmp0_getOrElse, index);
        } else {
          throw IndexOutOfBoundsException_init_$Create$_0("index: " + index + ", length: " + this.get_length_g42xv3_k$() + "}");
        }
        tmp$ret$0 = tmp;
        return tmp$ret$0;
      };
      StringBuilder.prototype.subSequence_5fh70h_k$ = function(startIndex, endIndex) {
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(startIndex, endIndex);
        return tmp$ret$1;
      };
      StringBuilder.prototype.append_t8oh9e_k$ = function(value) {
        var tmp0_this = this;
        tmp0_this.string_1 = tmp0_this.string_1 + new Char_0(value);
        return this;
      };
      StringBuilder.prototype.append_oz4qxs_k$ = function(value) {
        var tmp0_this = this;
        tmp0_this.string_1 = tmp0_this.string_1 + toString_0(value);
        return this;
      };
      StringBuilder.prototype.append_tbojcw_k$ = function(value, startIndex, endIndex) {
        var tmp0_elvis_lhs = value;
        return this.appendRange_mncs5k_k$(tmp0_elvis_lhs == null ? "null" : tmp0_elvis_lhs, startIndex, endIndex);
      };
      StringBuilder.prototype.reverse_i6tiw2_k$ = function() {
        var reversed2 = "";
        var index = this.string_1.length - 1 | 0;
        while (index >= 0) {
          var tmp = this.string_1;
          var tmp0 = index;
          index = tmp0 - 1 | 0;
          var low = charSequenceGet(tmp, tmp0);
          if (isLowSurrogate(low) ? index >= 0 : false) {
            var tmp_0 = this.string_1;
            var tmp1 = index;
            index = tmp1 - 1 | 0;
            var high = charSequenceGet(tmp_0, tmp1);
            if (isHighSurrogate(high)) {
              reversed2 = reversed2 + new Char_0(high) + new Char_0(low);
            } else {
              reversed2 = reversed2 + new Char_0(low) + new Char_0(high);
            }
          } else {
            reversed2 = reversed2 + new Char_0(low);
          }
        }
        this.string_1 = reversed2;
        return this;
      };
      StringBuilder.prototype.append_t8pm91_k$ = function(value) {
        var tmp0_this = this;
        tmp0_this.string_1 = tmp0_this.string_1 + toString_0(value);
        return this;
      };
      StringBuilder.prototype.append_a1id5s_k$ = function(value) {
        var tmp0_this = this;
        tmp0_this.string_1 = tmp0_this.string_1 + value;
        return this;
      };
      StringBuilder.prototype.append_18hb2z_k$ = function(value) {
        var tmp0_this = this;
        tmp0_this.string_1 = tmp0_this.string_1 + concatToString(value);
        return this;
      };
      StringBuilder.prototype.append_zar6u1_k$ = function(value) {
        return this.append_ssq29y_k$(value);
      };
      StringBuilder.prototype.append_ssq29y_k$ = function(value) {
        var tmp0_this = this;
        var tmp = tmp0_this;
        var tmp_0 = tmp0_this.string_1;
        var tmp1_elvis_lhs = value;
        tmp.string_1 = tmp_0 + (tmp1_elvis_lhs == null ? "null" : tmp1_elvis_lhs);
        return this;
      };
      StringBuilder.prototype.capacity_14dpom_k$ = function() {
        return this.get_length_g42xv3_k$();
      };
      StringBuilder.prototype.ensureCapacity_ignus8_k$ = function(minimumCapacity) {
      };
      StringBuilder.prototype.indexOf_kdecvs_k$ = function(string4) {
        var tmp$ret$0;
        var tmp0_asDynamic = this.string_1;
        tmp$ret$0 = tmp0_asDynamic;
        return tmp$ret$0.indexOf(string4);
      };
      StringBuilder.prototype.indexOf_sxnkg7_k$ = function(string4, startIndex) {
        var tmp$ret$0;
        var tmp0_asDynamic = this.string_1;
        tmp$ret$0 = tmp0_asDynamic;
        return tmp$ret$0.indexOf(string4, startIndex);
      };
      StringBuilder.prototype.lastIndexOf_my1yge_k$ = function(string4) {
        var tmp$ret$0;
        var tmp0_asDynamic = this.string_1;
        tmp$ret$0 = tmp0_asDynamic;
        return tmp$ret$0.lastIndexOf(string4);
      };
      StringBuilder.prototype.lastIndexOf_4awwhb_k$ = function(string4, startIndex) {
        var tmp;
        var tmp$ret$0;
        tmp$ret$0 = charSequenceLength(string4) === 0;
        if (tmp$ret$0) {
          tmp = startIndex < 0;
        } else {
          tmp = false;
        }
        if (tmp)
          return -1;
        var tmp$ret$1;
        var tmp0_asDynamic = this.string_1;
        tmp$ret$1 = tmp0_asDynamic;
        return tmp$ret$1.lastIndexOf(string4, startIndex);
      };
      StringBuilder.prototype.insert_ho1wgi_k$ = function(index, value) {
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this.get_length_g42xv3_k$());
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, index);
        var tmp_0 = tmp$ret$1 + value;
        var tmp$ret$3;
        var tmp1_substring = this.string_1;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_substring;
        tmp$ret$3 = tmp$ret$2.substring(index);
        tmp.string_1 = tmp_0 + tmp$ret$3;
        return this;
      };
      StringBuilder.prototype.insert_5hk2j8_k$ = function(index, value) {
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this.get_length_g42xv3_k$());
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, index);
        var tmp_0 = tmp$ret$1 + new Char_0(value);
        var tmp$ret$3;
        var tmp1_substring = this.string_1;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_substring;
        tmp$ret$3 = tmp$ret$2.substring(index);
        tmp.string_1 = tmp_0 + tmp$ret$3;
        return this;
      };
      StringBuilder.prototype.insert_5yqhyr_k$ = function(index, value) {
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this.get_length_g42xv3_k$());
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, index);
        var tmp_0 = tmp$ret$1 + concatToString(value);
        var tmp$ret$3;
        var tmp1_substring = this.string_1;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_substring;
        tmp$ret$3 = tmp$ret$2.substring(index);
        tmp.string_1 = tmp_0 + tmp$ret$3;
        return this;
      };
      StringBuilder.prototype.insert_xsudoy_k$ = function(index, value) {
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this.get_length_g42xv3_k$());
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, index);
        var tmp_0 = tmp$ret$1 + toString_0(value);
        var tmp$ret$3;
        var tmp1_substring = this.string_1;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_substring;
        tmp$ret$3 = tmp$ret$2.substring(index);
        tmp.string_1 = tmp_0 + tmp$ret$3;
        return this;
      };
      StringBuilder.prototype.insert_5hl7iv_k$ = function(index, value) {
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this.get_length_g42xv3_k$());
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, index);
        var tmp_0 = tmp$ret$1 + toString_0(value);
        var tmp$ret$3;
        var tmp1_substring = this.string_1;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_substring;
        tmp$ret$3 = tmp$ret$2.substring(index);
        tmp.string_1 = tmp_0 + tmp$ret$3;
        return this;
      };
      StringBuilder.prototype.insert_9mtcpl_k$ = function(index, value) {
        return this.insert_eitq2w_k$(index, value);
      };
      StringBuilder.prototype.insert_eitq2w_k$ = function(index, value) {
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this.get_length_g42xv3_k$());
        var tmp0_elvis_lhs = value;
        var toInsert = tmp0_elvis_lhs == null ? "null" : tmp0_elvis_lhs;
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, index);
        var tmp_0 = tmp$ret$1 + toInsert;
        var tmp$ret$3;
        var tmp1_substring = this.string_1;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_substring;
        tmp$ret$3 = tmp$ret$2.substring(index);
        tmp.string_1 = tmp_0 + tmp$ret$3;
        return this;
      };
      StringBuilder.prototype.setLength_kzn4fs_k$ = function(newLength) {
        if (newLength < 0) {
          throw IllegalArgumentException_init_$Create$_0("Negative new length: " + newLength + ".");
        }
        if (newLength <= this.get_length_g42xv3_k$()) {
          var tmp = this;
          var tmp$ret$1;
          var tmp0_substring = this.string_1;
          var tmp$ret$0;
          tmp$ret$0 = tmp0_substring;
          tmp$ret$1 = tmp$ret$0.substring(0, newLength);
          tmp.string_1 = tmp$ret$1;
        } else {
          var inductionVariable = this.get_length_g42xv3_k$();
          if (inductionVariable < newLength)
            do {
              var i = inductionVariable;
              inductionVariable = inductionVariable + 1 | 0;
              var tmp1_this = this;
              tmp1_this.string_1 = tmp1_this.string_1 + new Char_0(_Char___init__impl__6a9atx(0));
            } while (inductionVariable < newLength);
        }
      };
      StringBuilder.prototype.substring_ile4mo_k$ = function(startIndex) {
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(startIndex, this.get_length_g42xv3_k$());
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(startIndex);
        return tmp$ret$1;
      };
      StringBuilder.prototype.substring_8we4nj_k$ = function(startIndex, endIndex) {
        Companion_getInstance().checkBoundsIndexes_7787d9_k$(startIndex, endIndex, this.get_length_g42xv3_k$());
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(startIndex, endIndex);
        return tmp$ret$1;
      };
      StringBuilder.prototype.trimToSize_dnhilv_k$ = function() {
      };
      StringBuilder.prototype.toString = function() {
        return this.string_1;
      };
      StringBuilder.prototype.clear_1keqml_k$ = function() {
        this.string_1 = "";
        return this;
      };
      StringBuilder.prototype.set_jo4zce_k$ = function(index, value) {
        Companion_getInstance().checkElementIndex_ux0wz1_k$(index, this.get_length_g42xv3_k$());
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, index);
        var tmp_0 = tmp$ret$1 + new Char_0(value);
        var tmp$ret$3;
        var tmp1_substring = this.string_1;
        var tmp2_substring = index + 1 | 0;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_substring;
        tmp$ret$3 = tmp$ret$2.substring(tmp2_substring);
        tmp.string_1 = tmp_0 + tmp$ret$3;
      };
      StringBuilder.prototype.setRange_l2ldi2_k$ = function(startIndex, endIndex, value) {
        checkReplaceRange(this, startIndex, endIndex, this.get_length_g42xv3_k$());
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, startIndex);
        var tmp_0 = tmp$ret$1 + value;
        var tmp$ret$3;
        var tmp1_substring = this.string_1;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_substring;
        tmp$ret$3 = tmp$ret$2.substring(endIndex);
        tmp.string_1 = tmp_0 + tmp$ret$3;
        return this;
      };
      StringBuilder.prototype.deleteAt_w9fbwd_k$ = function(index) {
        Companion_getInstance().checkElementIndex_ux0wz1_k$(index, this.get_length_g42xv3_k$());
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, index);
        var tmp_0 = tmp$ret$1;
        var tmp$ret$3;
        var tmp1_substring = this.string_1;
        var tmp2_substring = index + 1 | 0;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_substring;
        tmp$ret$3 = tmp$ret$2.substring(tmp2_substring);
        tmp.string_1 = tmp_0 + tmp$ret$3;
        return this;
      };
      StringBuilder.prototype.deleteRange_ih0baq_k$ = function(startIndex, endIndex) {
        checkReplaceRange(this, startIndex, endIndex, this.get_length_g42xv3_k$());
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, startIndex);
        var tmp_0 = tmp$ret$1;
        var tmp$ret$3;
        var tmp1_substring = this.string_1;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_substring;
        tmp$ret$3 = tmp$ret$2.substring(endIndex);
        tmp.string_1 = tmp_0 + tmp$ret$3;
        return this;
      };
      StringBuilder.prototype.toCharArray_h4xf4t_k$ = function(destination, destinationOffset, startIndex, endIndex) {
        Companion_getInstance().checkBoundsIndexes_7787d9_k$(startIndex, endIndex, this.get_length_g42xv3_k$());
        Companion_getInstance().checkBoundsIndexes_7787d9_k$(destinationOffset, (destinationOffset + endIndex | 0) - startIndex | 0, destination.length);
        var dstIndex = destinationOffset;
        var inductionVariable = startIndex;
        if (inductionVariable < endIndex)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp1 = dstIndex;
            dstIndex = tmp1 + 1 | 0;
            destination[tmp1] = charSequenceGet(this.string_1, index);
          } while (inductionVariable < endIndex);
      };
      StringBuilder.prototype.toCharArray$default_x03qyo_k$ = function(destination, destinationOffset, startIndex, endIndex, $mask0, $handler) {
        if (!(($mask0 & 2) === 0))
          destinationOffset = 0;
        if (!(($mask0 & 4) === 0))
          startIndex = 0;
        if (!(($mask0 & 8) === 0))
          endIndex = this.get_length_g42xv3_k$();
        return this.toCharArray_h4xf4t_k$(destination, destinationOffset, startIndex, endIndex);
      };
      StringBuilder.prototype.appendRange_wizxgy_k$ = function(value, startIndex, endIndex) {
        var tmp0_this = this;
        tmp0_this.string_1 = tmp0_this.string_1 + concatToString_0(value, startIndex, endIndex);
        return this;
      };
      StringBuilder.prototype.appendRange_mncs5k_k$ = function(value, startIndex, endIndex) {
        var stringCsq = toString_1(value);
        Companion_getInstance().checkBoundsIndexes_7787d9_k$(startIndex, endIndex, stringCsq.length);
        var tmp0_this = this;
        var tmp = tmp0_this;
        var tmp_0 = tmp0_this.string_1;
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = stringCsq;
        tmp$ret$1 = tmp$ret$0.substring(startIndex, endIndex);
        tmp.string_1 = tmp_0 + tmp$ret$1;
        return this;
      };
      StringBuilder.prototype.insertRange_livkg8_k$ = function(index, value, startIndex, endIndex) {
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this.get_length_g42xv3_k$());
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, index);
        var tmp_0 = tmp$ret$1 + concatToString_0(value, startIndex, endIndex);
        var tmp$ret$3;
        var tmp1_substring = this.string_1;
        var tmp$ret$2;
        tmp$ret$2 = tmp1_substring;
        tmp$ret$3 = tmp$ret$2.substring(index);
        tmp.string_1 = tmp_0 + tmp$ret$3;
        return this;
      };
      StringBuilder.prototype.insertRange_rqhb2a_k$ = function(index, value, startIndex, endIndex) {
        Companion_getInstance().checkPositionIndex_kxpgsw_k$(index, this.get_length_g42xv3_k$());
        var stringCsq = toString_1(value);
        Companion_getInstance().checkBoundsIndexes_7787d9_k$(startIndex, endIndex, stringCsq.length);
        var tmp = this;
        var tmp$ret$1;
        var tmp0_substring = this.string_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_substring;
        tmp$ret$1 = tmp$ret$0.substring(0, index);
        var tmp_0 = tmp$ret$1;
        var tmp$ret$3;
        var tmp$ret$2;
        tmp$ret$2 = stringCsq;
        tmp$ret$3 = tmp$ret$2.substring(startIndex, endIndex);
        var tmp_1 = tmp_0 + tmp$ret$3;
        var tmp$ret$5;
        var tmp1_substring = this.string_1;
        var tmp$ret$4;
        tmp$ret$4 = tmp1_substring;
        tmp$ret$5 = tmp$ret$4.substring(index);
        tmp.string_1 = tmp_1 + tmp$ret$5;
        return this;
      };
      StringBuilder.$metadata$ = classMeta("StringBuilder", [Appendable, CharSequence]);
      function uppercaseChar(_this__u8e3s4) {
        var tmp$ret$2;
        var tmp$ret$1;
        var tmp$ret$0;
        var tmp0_asDynamic = toString(_this__u8e3s4);
        tmp$ret$0 = tmp0_asDynamic;
        var tmp1_unsafeCast = tmp$ret$0.toUpperCase();
        tmp$ret$1 = tmp1_unsafeCast;
        tmp$ret$2 = tmp$ret$1;
        var uppercase3 = tmp$ret$2;
        return uppercase3.length > 1 ? _this__u8e3s4 : charSequenceGet(uppercase3, 0);
      }
      function lowercaseChar(_this__u8e3s4) {
        var tmp$ret$2;
        var tmp$ret$1;
        var tmp$ret$0;
        var tmp0_asDynamic = toString(_this__u8e3s4);
        tmp$ret$0 = tmp0_asDynamic;
        var tmp1_unsafeCast = tmp$ret$0.toLowerCase();
        tmp$ret$1 = tmp1_unsafeCast;
        tmp$ret$2 = tmp$ret$1;
        return charSequenceGet(tmp$ret$2, 0);
      }
      function uppercase2(_this__u8e3s4) {
        var tmp$ret$1;
        var tmp$ret$0;
        var tmp0_asDynamic = toString(_this__u8e3s4);
        tmp$ret$0 = tmp0_asDynamic;
        var tmp1_unsafeCast = tmp$ret$0.toUpperCase();
        tmp$ret$1 = tmp1_unsafeCast;
        return tmp$ret$1;
      }
      function lowercase2(_this__u8e3s4) {
        var tmp$ret$1;
        var tmp$ret$0;
        var tmp0_asDynamic = toString(_this__u8e3s4);
        tmp$ret$0 = tmp0_asDynamic;
        var tmp1_unsafeCast = tmp$ret$0.toLowerCase();
        tmp$ret$1 = tmp1_unsafeCast;
        return tmp$ret$1;
      }
      function isLowSurrogate(_this__u8e3s4) {
        Companion_getInstance_18();
        var containsLower = _Char___init__impl__6a9atx(56320);
        var tmp;
        Companion_getInstance_18();
        if (_this__u8e3s4 <= _Char___init__impl__6a9atx(57343)) {
          tmp = containsLower <= _this__u8e3s4;
        } else {
          tmp = false;
        }
        return tmp;
      }
      function isHighSurrogate(_this__u8e3s4) {
        Companion_getInstance_18();
        var containsLower = _Char___init__impl__6a9atx(55296);
        var tmp;
        Companion_getInstance_18();
        if (_this__u8e3s4 <= _Char___init__impl__6a9atx(56319)) {
          tmp = containsLower <= _this__u8e3s4;
        } else {
          tmp = false;
        }
        return tmp;
      }
      function checkRadix(radix) {
        if (!(2 <= radix ? radix <= 36 : false)) {
          throw IllegalArgumentException_init_$Create$_0("radix " + radix + " was not in valid range 2..36");
        }
        return radix;
      }
      function get_STRING_CASE_INSENSITIVE_ORDER() {
        init_properties_string_kt_z8k4s7();
        return STRING_CASE_INSENSITIVE_ORDER;
      }
      var STRING_CASE_INSENSITIVE_ORDER;
      function nativeLastIndexOf(_this__u8e3s4, str, fromIndex) {
        init_properties_string_kt_z8k4s7();
        var tmp$ret$0;
        tmp$ret$0 = _this__u8e3s4;
        return tmp$ret$0.lastIndexOf(str, fromIndex);
      }
      function substring(_this__u8e3s4, startIndex, endIndex) {
        init_properties_string_kt_z8k4s7();
        var tmp$ret$0;
        tmp$ret$0 = _this__u8e3s4;
        return tmp$ret$0.substring(startIndex, endIndex);
      }
      function substring_0(_this__u8e3s4, startIndex) {
        init_properties_string_kt_z8k4s7();
        var tmp$ret$0;
        tmp$ret$0 = _this__u8e3s4;
        return tmp$ret$0.substring(startIndex);
      }
      function compareTo(_this__u8e3s4, other, ignoreCase) {
        init_properties_string_kt_z8k4s7();
        if (ignoreCase) {
          var n1 = _this__u8e3s4.length;
          var n2 = other.length;
          var tmp$ret$0;
          tmp$ret$0 = Math.min(n1, n2);
          var min2 = tmp$ret$0;
          if (min2 === 0)
            return n1 - n2 | 0;
          var inductionVariable = 0;
          if (inductionVariable < min2)
            do {
              var index = inductionVariable;
              inductionVariable = inductionVariable + 1 | 0;
              var thisChar = charSequenceGet(_this__u8e3s4, index);
              var otherChar = charSequenceGet(other, index);
              if (!equals(new Char_0(thisChar), new Char_0(otherChar))) {
                thisChar = uppercaseChar(thisChar);
                otherChar = uppercaseChar(otherChar);
                if (!equals(new Char_0(thisChar), new Char_0(otherChar))) {
                  var tmp$ret$4;
                  var tmp0_lowercaseChar = thisChar;
                  var tmp$ret$3;
                  var tmp$ret$2;
                  var tmp$ret$1;
                  var tmp0_asDynamic = toString(tmp0_lowercaseChar);
                  tmp$ret$1 = tmp0_asDynamic;
                  var tmp1_unsafeCast = tmp$ret$1.toLowerCase();
                  tmp$ret$2 = tmp1_unsafeCast;
                  tmp$ret$3 = tmp$ret$2;
                  tmp$ret$4 = charSequenceGet(tmp$ret$3, 0);
                  thisChar = tmp$ret$4;
                  var tmp$ret$8;
                  var tmp1_lowercaseChar = otherChar;
                  var tmp$ret$7;
                  var tmp$ret$6;
                  var tmp$ret$5;
                  var tmp0_asDynamic_0 = toString(tmp1_lowercaseChar);
                  tmp$ret$5 = tmp0_asDynamic_0;
                  var tmp1_unsafeCast_0 = tmp$ret$5.toLowerCase();
                  tmp$ret$6 = tmp1_unsafeCast_0;
                  tmp$ret$7 = tmp$ret$6;
                  tmp$ret$8 = charSequenceGet(tmp$ret$7, 0);
                  otherChar = tmp$ret$8;
                  if (!equals(new Char_0(thisChar), new Char_0(otherChar))) {
                    return Char__compareTo_impl_ypi4mb(thisChar, otherChar);
                  }
                }
              }
            } while (inductionVariable < min2);
          return n1 - n2 | 0;
        } else {
          return compareTo_0(_this__u8e3s4, other);
        }
      }
      function compareTo$default(_this__u8e3s4, other, ignoreCase, $mask0, $handler) {
        if (!(($mask0 & 2) === 0))
          ignoreCase = false;
        return compareTo(_this__u8e3s4, other, ignoreCase);
      }
      function concatToString(_this__u8e3s4) {
        init_properties_string_kt_z8k4s7();
        var result = "";
        var indexedObject = _this__u8e3s4;
        var inductionVariable = 0;
        var last = indexedObject.length;
        while (inductionVariable < last) {
          var char = indexedObject[inductionVariable];
          inductionVariable = inductionVariable + 1 | 0;
          result = result + new Char_0(char);
        }
        return result;
      }
      function concatToString_0(_this__u8e3s4, startIndex, endIndex) {
        init_properties_string_kt_z8k4s7();
        Companion_getInstance().checkBoundsIndexes_7787d9_k$(startIndex, endIndex, _this__u8e3s4.length);
        var result = "";
        var inductionVariable = startIndex;
        if (inductionVariable < endIndex)
          do {
            var index = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            result = result + new Char_0(_this__u8e3s4[index]);
          } while (inductionVariable < endIndex);
        return result;
      }
      function concatToString$default(_this__u8e3s4, startIndex, endIndex, $mask0, $handler) {
        if (!(($mask0 & 1) === 0))
          startIndex = 0;
        if (!(($mask0 & 2) === 0))
          endIndex = _this__u8e3s4.length;
        return concatToString_0(_this__u8e3s4, startIndex, endIndex);
      }
      function sam$kotlin_Comparator$0(function_0) {
        this.function_1 = function_0;
      }
      sam$kotlin_Comparator$0.prototype.compare_6tbigh_k$ = function(a, b) {
        return this.function_1(a, b);
      };
      sam$kotlin_Comparator$0.prototype.compare = function(a, b) {
        return this.compare_6tbigh_k$(a, b);
      };
      sam$kotlin_Comparator$0.$metadata$ = classMeta("sam$kotlin_Comparator$0", [Comparator]);
      function STRING_CASE_INSENSITIVE_ORDER$lambda(a, b) {
        init_properties_string_kt_z8k4s7();
        return compareTo(a, b, true);
      }
      var properties_initialized_string_kt_4g1sj;
      function init_properties_string_kt_z8k4s7() {
        if (properties_initialized_string_kt_4g1sj) {
        } else {
          properties_initialized_string_kt_4g1sj = true;
          var tmp = STRING_CASE_INSENSITIVE_ORDER$lambda;
          STRING_CASE_INSENSITIVE_ORDER = new sam$kotlin_Comparator$0(tmp);
        }
      }
      function get_REPLACEMENT_BYTE_SEQUENCE() {
        init_properties_utf8Encoding_kt_xjxnfa();
        return REPLACEMENT_BYTE_SEQUENCE;
      }
      var REPLACEMENT_BYTE_SEQUENCE;
      var properties_initialized_utf8Encoding_kt_eee1vq;
      function init_properties_utf8Encoding_kt_xjxnfa() {
        if (properties_initialized_utf8Encoding_kt_eee1vq) {
        } else {
          properties_initialized_utf8Encoding_kt_eee1vq = true;
          var tmp$ret$0;
          var tmp0_byteArrayOf = new Int8Array([-17, -65, -67]);
          tmp$ret$0 = tmp0_byteArrayOf;
          REPLACEMENT_BYTE_SEQUENCE = tmp$ret$0;
        }
      }
      function _Char___init__impl__6a9atx(value) {
        return value;
      }
      function _get_value__a43j40($this) {
        return $this;
      }
      function _Char___init__impl__6a9atx_0(code) {
        var tmp$ret$0;
        tmp$ret$0 = _UShort___get_data__impl__g0245(code) & 65535;
        var tmp = _Char___init__impl__6a9atx(tmp$ret$0);
        return tmp;
      }
      function Char__compareTo_impl_ypi4mb($this, other) {
        return _get_value__a43j40($this) - _get_value__a43j40(other) | 0;
      }
      function Char__compareTo_impl_ypi4mb_0($this, other) {
        var tmp = $this.value_1;
        return Char__compareTo_impl_ypi4mb(tmp, other instanceof Char_0 ? other.value_1 : THROW_CCE());
      }
      function Char__plus_impl_qi7pgj($this, other) {
        return numberToChar(_get_value__a43j40($this) + other | 0);
      }
      function Char__minus_impl_a2frrh($this, other) {
        return _get_value__a43j40($this) - _get_value__a43j40(other) | 0;
      }
      function Char__minus_impl_a2frrh_0($this, other) {
        return numberToChar(_get_value__a43j40($this) - other | 0);
      }
      function Char__inc_impl_6e1wmz($this) {
        return numberToChar(_get_value__a43j40($this) + 1 | 0);
      }
      function Char__dec_impl_1ipdy9($this) {
        return numberToChar(_get_value__a43j40($this) - 1 | 0);
      }
      function Char__rangeTo_impl_tkncvp($this, other) {
        return new CharRange($this, other);
      }
      function Char__toByte_impl_7s7yt0($this) {
        return toByte(_get_value__a43j40($this));
      }
      function Char__toChar_impl_3h7tei($this) {
        return $this;
      }
      function Char__toShort_impl_7qagse($this) {
        return toShort(_get_value__a43j40($this));
      }
      function Char__toInt_impl_vasixd($this) {
        return _get_value__a43j40($this);
      }
      function Char__toLong_impl_r7eygw($this) {
        return toLong(_get_value__a43j40($this));
      }
      function Char__toFloat_impl_kl2gf6($this) {
        return _get_value__a43j40($this);
      }
      function Char__toDouble_impl_jaecy3($this) {
        return _get_value__a43j40($this);
      }
      function Char__equals_impl_x6719k($this, other) {
        if (!(other instanceof Char_0))
          return false;
        return _get_value__a43j40($this) === _get_value__a43j40(other.value_1);
      }
      function Char__hashCode_impl_otmys($this) {
        return _get_value__a43j40($this);
      }
      function toString($this) {
        var tmp$ret$0;
        var tmp0_unsafeCast = String.fromCharCode(_get_value__a43j40($this));
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function Companion_18() {
        Companion_instance_18 = this;
        this.MIN_VALUE_1 = _Char___init__impl__6a9atx(0);
        this.MAX_VALUE_1 = _Char___init__impl__6a9atx(65535);
        this.MIN_HIGH_SURROGATE_1 = _Char___init__impl__6a9atx(55296);
        this.MAX_HIGH_SURROGATE_1 = _Char___init__impl__6a9atx(56319);
        this.MIN_LOW_SURROGATE_1 = _Char___init__impl__6a9atx(56320);
        this.MAX_LOW_SURROGATE_1 = _Char___init__impl__6a9atx(57343);
        this.MIN_SURROGATE_1 = _Char___init__impl__6a9atx(55296);
        this.MAX_SURROGATE_1 = _Char___init__impl__6a9atx(57343);
        this.SIZE_BYTES_1 = 2;
        this.SIZE_BITS_1 = 16;
      }
      Companion_18.prototype.get_MIN_VALUE_9yp2os_k$ = function() {
        return this.MIN_VALUE_1;
      };
      Companion_18.prototype.get_MAX_VALUE_blimwe_k$ = function() {
        return this.MAX_VALUE_1;
      };
      Companion_18.prototype.get_MIN_HIGH_SURROGATE_t7mej6_k$ = function() {
        return this.MIN_HIGH_SURROGATE_1;
      };
      Companion_18.prototype.get_MAX_HIGH_SURROGATE_eb6erk_k$ = function() {
        return this.MAX_HIGH_SURROGATE_1;
      };
      Companion_18.prototype.get_MIN_LOW_SURROGATE_mxezgo_k$ = function() {
        return this.MIN_LOW_SURROGATE_1;
      };
      Companion_18.prototype.get_MAX_LOW_SURROGATE_gwteoa_k$ = function() {
        return this.MAX_LOW_SURROGATE_1;
      };
      Companion_18.prototype.get_MIN_SURROGATE_6vpmm5_k$ = function() {
        return this.MIN_SURROGATE_1;
      };
      Companion_18.prototype.get_MAX_SURROGATE_r8jfhn_k$ = function() {
        return this.MAX_SURROGATE_1;
      };
      Companion_18.prototype.get_SIZE_BYTES_qphg4q_k$ = function() {
        return this.SIZE_BYTES_1;
      };
      Companion_18.prototype.get_SIZE_BITS_7qhjj9_k$ = function() {
        return this.SIZE_BITS_1;
      };
      Companion_18.$metadata$ = objectMeta("Companion");
      var Companion_instance_18;
      function Companion_getInstance_18() {
        if (Companion_instance_18 == null)
          new Companion_18();
        return Companion_instance_18;
      }
      function Char_0(value) {
        Companion_getInstance_18();
        this.value_1 = value;
      }
      Char_0.prototype.compareTo_n49u4k_k$ = function(other) {
        return Char__compareTo_impl_ypi4mb(this.value_1, other);
      };
      Char_0.prototype.compareTo_6thzaj_k$ = function(other) {
        return Char__compareTo_impl_ypi4mb_0(this, other);
      };
      Char_0.prototype.equals = function(other) {
        return Char__equals_impl_x6719k(this.value_1, other);
      };
      Char_0.prototype.hashCode = function() {
        return Char__hashCode_impl_otmys(this.value_1);
      };
      Char_0.prototype.toString = function() {
        return toString(this.value_1);
      };
      Char_0.$metadata$ = classMeta("Char", [Comparable]);
      function Iterable() {
      }
      Iterable.$metadata$ = interfaceMeta("Iterable");
      function MutableList() {
      }
      MutableList.$metadata$ = interfaceMeta("MutableList", [List, MutableCollection]);
      function Collection() {
      }
      Collection.$metadata$ = interfaceMeta("Collection", [Iterable]);
      function List() {
      }
      List.$metadata$ = interfaceMeta("List", [Collection]);
      function MutableCollection() {
      }
      MutableCollection.$metadata$ = interfaceMeta("MutableCollection", [Collection, MutableIterable]);
      function MutableIterable() {
      }
      MutableIterable.$metadata$ = interfaceMeta("MutableIterable", [Iterable]);
      function Set2() {
      }
      Set2.$metadata$ = interfaceMeta("Set", [Collection]);
      function Entry() {
      }
      Entry.$metadata$ = interfaceMeta("Entry");
      function Map2() {
      }
      Map2.$metadata$ = interfaceMeta("Map");
      function MutableSet() {
      }
      MutableSet.$metadata$ = interfaceMeta("MutableSet", [Set2, MutableCollection]);
      function MutableEntry() {
      }
      MutableEntry.$metadata$ = interfaceMeta("MutableEntry", [Entry]);
      function MutableMap() {
      }
      MutableMap.$metadata$ = interfaceMeta("MutableMap", [Map2]);
      function Companion_19() {
        Companion_instance_19 = this;
      }
      Companion_19.$metadata$ = objectMeta("Companion");
      var Companion_instance_19;
      function Companion_getInstance_19() {
        if (Companion_instance_19 == null)
          new Companion_19();
        return Companion_instance_19;
      }
      function Enum(name, ordinal) {
        Companion_getInstance_19();
        this.name_1 = name;
        this.ordinal_1 = ordinal;
      }
      Enum.prototype.get_name_woqyms_k$ = function() {
        return this.name_1;
      };
      Enum.prototype.get_ordinal_ip24qg_k$ = function() {
        return this.ordinal_1;
      };
      Enum.prototype.compareTo_6thzay_k$ = function(other) {
        return compareTo_0(this.ordinal_1, other.ordinal_1);
      };
      Enum.prototype.compareTo_6thzaj_k$ = function(other) {
        return this.compareTo_6thzay_k$(other instanceof Enum ? other : THROW_CCE());
      };
      Enum.prototype.equals = function(other) {
        return this === other;
      };
      Enum.prototype.hashCode = function() {
        return identityHashCode(this);
      };
      Enum.prototype.toString = function() {
        return this.name_1;
      };
      Enum.$metadata$ = classMeta("Enum", [Comparable]);
      function byteArrayOf(elements) {
        return elements;
      }
      function arrayOf(elements) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = elements;
        tmp$ret$1 = tmp$ret$0;
        return tmp$ret$1;
      }
      function intArrayOf(elements) {
        return elements;
      }
      function doubleArrayOf(elements) {
        return elements;
      }
      function toString_0(_this__u8e3s4) {
        var tmp0_safe_receiver = _this__u8e3s4;
        var tmp1_elvis_lhs = tmp0_safe_receiver == null ? null : toString_1(tmp0_safe_receiver);
        return tmp1_elvis_lhs == null ? "null" : tmp1_elvis_lhs;
      }
      function plus_0(_this__u8e3s4, other) {
        var tmp2_safe_receiver = _this__u8e3s4;
        var tmp3_elvis_lhs = tmp2_safe_receiver == null ? null : toString_1(tmp2_safe_receiver);
        var tmp = tmp3_elvis_lhs == null ? "null" : tmp3_elvis_lhs;
        var tmp0_safe_receiver = other;
        var tmp1_elvis_lhs = tmp0_safe_receiver == null ? null : toString_1(tmp0_safe_receiver);
        return tmp + (tmp1_elvis_lhs == null ? "null" : tmp1_elvis_lhs);
      }
      function DefaultConstructorMarker() {
        DefaultConstructorMarker_instance = this;
      }
      DefaultConstructorMarker.$metadata$ = objectMeta("DefaultConstructorMarker");
      var DefaultConstructorMarker_instance;
      function DefaultConstructorMarker_getInstance() {
        if (DefaultConstructorMarker_instance == null)
          new DefaultConstructorMarker();
        return DefaultConstructorMarker_instance;
      }
      function fillArrayVal(array3, initValue) {
        var inductionVariable = 0;
        var last = array3.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            array3[i] = initValue;
          } while (!(i === last));
        return array3;
      }
      function arrayWithFun(size2, init2) {
        var tmp$ret$1;
        var tmp0_fillArrayFun = Array(size2);
        var tmp$ret$0;
        tmp$ret$0 = tmp0_fillArrayFun;
        var result = tmp$ret$0;
        var i = 0;
        while (!(i === result.length)) {
          result[i] = init2(i);
          i = i + 1 | 0;
        }
        tmp$ret$1 = result;
        return tmp$ret$1;
      }
      function fillArrayFun(array3, init2) {
        var tmp$ret$0;
        tmp$ret$0 = array3;
        var result = tmp$ret$0;
        var i = 0;
        while (!(i === result.length)) {
          result[i] = init2(i);
          i = i + 1 | 0;
        }
        return result;
      }
      function arrayIterator(array3) {
        return new arrayIterator$1(array3);
      }
      function booleanArrayIterator(array3) {
        return new booleanArrayIterator$1(array3);
      }
      function charArrayIterator(array3) {
        return new charArrayIterator$1(array3);
      }
      function byteArrayIterator(array3) {
        return new byteArrayIterator$1(array3);
      }
      function shortArrayIterator(array3) {
        return new shortArrayIterator$1(array3);
      }
      function intArrayIterator(array3) {
        return new intArrayIterator$1(array3);
      }
      function floatArrayIterator(array3) {
        return new floatArrayIterator$1(array3);
      }
      function longArrayIterator(array3) {
        return new longArrayIterator$1(array3);
      }
      function doubleArrayIterator(array3) {
        return new doubleArrayIterator$1(array3);
      }
      function booleanArray(size2) {
        var tmp$ret$1;
        var tmp$ret$0;
        var tmp0_withType = fillArrayVal(Array(size2), false);
        tmp0_withType.$type$ = "BooleanArray";
        tmp$ret$0 = tmp0_withType;
        var tmp1_unsafeCast = tmp$ret$0;
        tmp$ret$1 = tmp1_unsafeCast;
        return tmp$ret$1;
      }
      function charArray(size2) {
        var tmp$ret$1;
        var tmp$ret$0;
        var tmp0_withType = new Uint16Array(size2);
        tmp0_withType.$type$ = "CharArray";
        tmp$ret$0 = tmp0_withType;
        var tmp1_unsafeCast = tmp$ret$0;
        tmp$ret$1 = tmp1_unsafeCast;
        return tmp$ret$1;
      }
      function longArray(size2) {
        var tmp$ret$1;
        var tmp$ret$0;
        var tmp0_withType = fillArrayVal(Array(size2), new Long(0, 0));
        tmp0_withType.$type$ = "LongArray";
        tmp$ret$0 = tmp0_withType;
        var tmp1_unsafeCast = tmp$ret$0;
        tmp$ret$1 = tmp1_unsafeCast;
        return tmp$ret$1;
      }
      function booleanArrayOf(arr) {
        var tmp$ret$2;
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = arr;
        var tmp0_withType = tmp$ret$0.slice();
        tmp0_withType.$type$ = "BooleanArray";
        tmp$ret$1 = tmp0_withType;
        var tmp1_unsafeCast = tmp$ret$1;
        tmp$ret$2 = tmp1_unsafeCast;
        return tmp$ret$2;
      }
      function charArrayOf(arr) {
        var tmp$ret$1;
        var tmp$ret$0;
        var tmp0_withType = new Uint16Array(arr);
        tmp0_withType.$type$ = "CharArray";
        tmp$ret$0 = tmp0_withType;
        var tmp1_unsafeCast = tmp$ret$0;
        tmp$ret$1 = tmp1_unsafeCast;
        return tmp$ret$1;
      }
      function longArrayOf(arr) {
        var tmp$ret$2;
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = arr;
        var tmp0_withType = tmp$ret$0.slice();
        tmp0_withType.$type$ = "LongArray";
        tmp$ret$1 = tmp0_withType;
        var tmp1_unsafeCast = tmp$ret$1;
        tmp$ret$2 = tmp1_unsafeCast;
        return tmp$ret$2;
      }
      function arrayIterator$1($array) {
        this.$array_1 = $array;
        this.index_1 = 0;
      }
      arrayIterator$1.prototype.set_index_eknhut_k$ = function(_set____db54di) {
        this.index_1 = _set____db54di;
      };
      arrayIterator$1.prototype.get_index_it478p_k$ = function() {
        return this.index_1;
      };
      arrayIterator$1.prototype.hasNext_bitz1p_k$ = function() {
        return !(this.index_1 === this.$array_1.length);
      };
      arrayIterator$1.prototype.next_20eer_k$ = function() {
        var tmp;
        if (!(this.index_1 === this.$array_1.length)) {
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          tmp = this.$array_1[tmp1];
        } else {
          throw NoSuchElementException_init_$Create$_0("" + this.index_1);
        }
        return tmp;
      };
      arrayIterator$1.$metadata$ = classMeta(void 0, [Iterator_3]);
      function booleanArrayIterator$1($array) {
        this.$array_1 = $array;
        BooleanIterator.call(this);
        this.index_1 = 0;
      }
      booleanArrayIterator$1.prototype.set_index_eknhut_k$ = function(_set____db54di) {
        this.index_1 = _set____db54di;
      };
      booleanArrayIterator$1.prototype.get_index_it478p_k$ = function() {
        return this.index_1;
      };
      booleanArrayIterator$1.prototype.hasNext_bitz1p_k$ = function() {
        return !(this.index_1 === this.$array_1.length);
      };
      booleanArrayIterator$1.prototype.nextBoolean_nfdk1h_k$ = function() {
        var tmp;
        if (!(this.index_1 === this.$array_1.length)) {
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          tmp = this.$array_1[tmp1];
        } else {
          throw NoSuchElementException_init_$Create$_0("" + this.index_1);
        }
        return tmp;
      };
      booleanArrayIterator$1.$metadata$ = classMeta(void 0, void 0, void 0, void 0, void 0, BooleanIterator.prototype);
      function charArrayIterator$1($array) {
        this.$array_1 = $array;
        CharIterator.call(this);
        this.index_1 = 0;
      }
      charArrayIterator$1.prototype.set_index_eknhut_k$ = function(_set____db54di) {
        this.index_1 = _set____db54di;
      };
      charArrayIterator$1.prototype.get_index_it478p_k$ = function() {
        return this.index_1;
      };
      charArrayIterator$1.prototype.hasNext_bitz1p_k$ = function() {
        return !(this.index_1 === this.$array_1.length);
      };
      charArrayIterator$1.prototype.nextChar_yv3rl6_k$ = function() {
        var tmp;
        if (!(this.index_1 === this.$array_1.length)) {
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          tmp = this.$array_1[tmp1];
        } else {
          throw NoSuchElementException_init_$Create$_0("" + this.index_1);
        }
        return tmp;
      };
      charArrayIterator$1.$metadata$ = classMeta(void 0, void 0, void 0, void 0, void 0, CharIterator.prototype);
      function byteArrayIterator$1($array) {
        this.$array_1 = $array;
        ByteIterator.call(this);
        this.index_1 = 0;
      }
      byteArrayIterator$1.prototype.set_index_eknhut_k$ = function(_set____db54di) {
        this.index_1 = _set____db54di;
      };
      byteArrayIterator$1.prototype.get_index_it478p_k$ = function() {
        return this.index_1;
      };
      byteArrayIterator$1.prototype.hasNext_bitz1p_k$ = function() {
        return !(this.index_1 === this.$array_1.length);
      };
      byteArrayIterator$1.prototype.nextByte_njqopn_k$ = function() {
        var tmp;
        if (!(this.index_1 === this.$array_1.length)) {
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          tmp = this.$array_1[tmp1];
        } else {
          throw NoSuchElementException_init_$Create$_0("" + this.index_1);
        }
        return tmp;
      };
      byteArrayIterator$1.$metadata$ = classMeta(void 0, void 0, void 0, void 0, void 0, ByteIterator.prototype);
      function shortArrayIterator$1($array) {
        this.$array_1 = $array;
        ShortIterator.call(this);
        this.index_1 = 0;
      }
      shortArrayIterator$1.prototype.set_index_eknhut_k$ = function(_set____db54di) {
        this.index_1 = _set____db54di;
      };
      shortArrayIterator$1.prototype.get_index_it478p_k$ = function() {
        return this.index_1;
      };
      shortArrayIterator$1.prototype.hasNext_bitz1p_k$ = function() {
        return !(this.index_1 === this.$array_1.length);
      };
      shortArrayIterator$1.prototype.nextShort_jxwabt_k$ = function() {
        var tmp;
        if (!(this.index_1 === this.$array_1.length)) {
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          tmp = this.$array_1[tmp1];
        } else {
          throw NoSuchElementException_init_$Create$_0("" + this.index_1);
        }
        return tmp;
      };
      shortArrayIterator$1.$metadata$ = classMeta(void 0, void 0, void 0, void 0, void 0, ShortIterator.prototype);
      function intArrayIterator$1($array) {
        this.$array_1 = $array;
        IntIterator.call(this);
        this.index_1 = 0;
      }
      intArrayIterator$1.prototype.set_index_eknhut_k$ = function(_set____db54di) {
        this.index_1 = _set____db54di;
      };
      intArrayIterator$1.prototype.get_index_it478p_k$ = function() {
        return this.index_1;
      };
      intArrayIterator$1.prototype.hasNext_bitz1p_k$ = function() {
        return !(this.index_1 === this.$array_1.length);
      };
      intArrayIterator$1.prototype.nextInt_ujorgc_k$ = function() {
        var tmp;
        if (!(this.index_1 === this.$array_1.length)) {
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          tmp = this.$array_1[tmp1];
        } else {
          throw NoSuchElementException_init_$Create$_0("" + this.index_1);
        }
        return tmp;
      };
      intArrayIterator$1.$metadata$ = classMeta(void 0, void 0, void 0, void 0, void 0, IntIterator.prototype);
      function floatArrayIterator$1($array) {
        this.$array_1 = $array;
        FloatIterator.call(this);
        this.index_1 = 0;
      }
      floatArrayIterator$1.prototype.set_index_eknhut_k$ = function(_set____db54di) {
        this.index_1 = _set____db54di;
      };
      floatArrayIterator$1.prototype.get_index_it478p_k$ = function() {
        return this.index_1;
      };
      floatArrayIterator$1.prototype.hasNext_bitz1p_k$ = function() {
        return !(this.index_1 === this.$array_1.length);
      };
      floatArrayIterator$1.prototype.nextFloat_jqti5l_k$ = function() {
        var tmp;
        if (!(this.index_1 === this.$array_1.length)) {
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          tmp = this.$array_1[tmp1];
        } else {
          throw NoSuchElementException_init_$Create$_0("" + this.index_1);
        }
        return tmp;
      };
      floatArrayIterator$1.$metadata$ = classMeta(void 0, void 0, void 0, void 0, void 0, FloatIterator.prototype);
      function longArrayIterator$1($array) {
        this.$array_1 = $array;
        LongIterator.call(this);
        this.index_1 = 0;
      }
      longArrayIterator$1.prototype.set_index_eknhut_k$ = function(_set____db54di) {
        this.index_1 = _set____db54di;
      };
      longArrayIterator$1.prototype.get_index_it478p_k$ = function() {
        return this.index_1;
      };
      longArrayIterator$1.prototype.hasNext_bitz1p_k$ = function() {
        return !(this.index_1 === this.$array_1.length);
      };
      longArrayIterator$1.prototype.nextLong_njwv0v_k$ = function() {
        var tmp;
        if (!(this.index_1 === this.$array_1.length)) {
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          tmp = this.$array_1[tmp1];
        } else {
          throw NoSuchElementException_init_$Create$_0("" + this.index_1);
        }
        return tmp;
      };
      longArrayIterator$1.$metadata$ = classMeta(void 0, void 0, void 0, void 0, void 0, LongIterator.prototype);
      function doubleArrayIterator$1($array) {
        this.$array_1 = $array;
        DoubleIterator.call(this);
        this.index_1 = 0;
      }
      doubleArrayIterator$1.prototype.set_index_eknhut_k$ = function(_set____db54di) {
        this.index_1 = _set____db54di;
      };
      doubleArrayIterator$1.prototype.get_index_it478p_k$ = function() {
        return this.index_1;
      };
      doubleArrayIterator$1.prototype.hasNext_bitz1p_k$ = function() {
        return !(this.index_1 === this.$array_1.length);
      };
      doubleArrayIterator$1.prototype.nextDouble_s2xvfg_k$ = function() {
        var tmp;
        if (!(this.index_1 === this.$array_1.length)) {
          var tmp0_this = this;
          var tmp1 = tmp0_this.index_1;
          tmp0_this.index_1 = tmp1 + 1 | 0;
          tmp = this.$array_1[tmp1];
        } else {
          throw NoSuchElementException_init_$Create$_0("" + this.index_1);
        }
        return tmp;
      };
      doubleArrayIterator$1.$metadata$ = classMeta(void 0, void 0, void 0, void 0, void 0, DoubleIterator.prototype);
      function get_buf() {
        init_properties_bitUtils_kt_cxtw9i();
        return buf;
      }
      var buf;
      function get_bufFloat64() {
        init_properties_bitUtils_kt_cxtw9i();
        return bufFloat64;
      }
      var bufFloat64;
      function get_bufFloat32() {
        init_properties_bitUtils_kt_cxtw9i();
        return bufFloat32;
      }
      var bufFloat32;
      function get_bufInt32() {
        init_properties_bitUtils_kt_cxtw9i();
        return bufInt32;
      }
      var bufInt32;
      function get_lowIndex() {
        init_properties_bitUtils_kt_cxtw9i();
        return lowIndex;
      }
      var lowIndex;
      function get_highIndex() {
        init_properties_bitUtils_kt_cxtw9i();
        return highIndex;
      }
      var highIndex;
      function doubleFromBits(value) {
        init_properties_bitUtils_kt_cxtw9i();
        get_bufInt32()[get_lowIndex()] = value.low_1;
        get_bufInt32()[get_highIndex()] = value.high_1;
        return get_bufFloat64()[0];
      }
      function doubleToRawBits(value) {
        init_properties_bitUtils_kt_cxtw9i();
        get_bufFloat64()[0] = value;
        return new Long(get_bufInt32()[get_lowIndex()], get_bufInt32()[get_highIndex()]);
      }
      function getNumberHashCode(obj) {
        init_properties_bitUtils_kt_cxtw9i();
        var tmp$ret$1;
        var tmp0_unsafeCast = jsBitwiseOr(obj, 0);
        var tmp$ret$0;
        tmp$ret$0 = tmp0_unsafeCast;
        tmp$ret$1 = tmp$ret$0;
        if (tmp$ret$1 === obj) {
          return numberToInt(obj);
        }
        get_bufFloat64()[0] = obj;
        return imul(get_bufInt32()[get_highIndex()], 31) + get_bufInt32()[get_lowIndex()] | 0;
      }
      var properties_initialized_bitUtils_kt_i2bo3e;
      function init_properties_bitUtils_kt_cxtw9i() {
        if (properties_initialized_bitUtils_kt_i2bo3e) {
        } else {
          properties_initialized_bitUtils_kt_i2bo3e = true;
          buf = new ArrayBuffer(8);
          var tmp$ret$1;
          var tmp0_unsafeCast = new Float64Array(get_buf());
          var tmp$ret$0;
          tmp$ret$0 = tmp0_unsafeCast;
          tmp$ret$1 = tmp$ret$0;
          bufFloat64 = tmp$ret$1;
          var tmp$ret$1_0;
          var tmp0_unsafeCast_0 = new Float32Array(get_buf());
          var tmp$ret$0_0;
          tmp$ret$0_0 = tmp0_unsafeCast_0;
          tmp$ret$1_0 = tmp$ret$0_0;
          bufFloat32 = tmp$ret$1_0;
          var tmp$ret$1_1;
          var tmp0_unsafeCast_1 = new Int32Array(get_buf());
          var tmp$ret$0_1;
          tmp$ret$0_1 = tmp0_unsafeCast_1;
          tmp$ret$1_1 = tmp$ret$0_1;
          bufInt32 = tmp$ret$1_1;
          var tmp$ret$1_2;
          var tmp$ret$0_2;
          get_bufFloat64()[0] = -1;
          tmp$ret$0_2 = !(get_bufInt32()[0] === 0) ? 1 : 0;
          tmp$ret$1_2 = tmp$ret$0_2;
          lowIndex = tmp$ret$1_2;
          highIndex = 1 - get_lowIndex() | 0;
        }
      }
      function booleanInExternalLog(name, obj) {
        if (!(typeof obj === "boolean")) {
          var tmp$ret$0;
          var tmp0_asDynamic = console;
          tmp$ret$0 = tmp0_asDynamic;
          tmp$ret$0.error("Boolean expected for '" + name + "', but actual:", obj);
        }
      }
      function booleanInExternalException(name, obj) {
        if (!(typeof obj === "boolean")) {
          throw new Error("Boolean expected for '" + name + "', but actual: " + obj);
        }
      }
      function DoNotIntrinsify() {
      }
      DoNotIntrinsify.prototype.equals = function(other) {
        if (!(other instanceof DoNotIntrinsify))
          return false;
        var tmp0_other_with_cast = other instanceof DoNotIntrinsify ? other : THROW_CCE();
        return true;
      };
      DoNotIntrinsify.prototype.hashCode = function() {
        return 0;
      };
      DoNotIntrinsify.prototype.toString = function() {
        return "@kotlin.js.DoNotIntrinsify()";
      };
      DoNotIntrinsify.$metadata$ = classMeta("DoNotIntrinsify", [Annotation]);
      function charSequenceGet(a, index) {
        var tmp;
        if (isString2(a)) {
          var tmp$ret$4;
          var tmp$ret$1;
          var tmp$ret$0;
          tmp$ret$0 = a;
          var tmp0_unsafeCast = tmp$ret$0.charCodeAt(index);
          tmp$ret$1 = tmp0_unsafeCast;
          var tmp1_Char = tmp$ret$1;
          var tmp_0;
          var tmp$ret$2;
          Companion_getInstance_18();
          var tmp0__get_code__88qj9g = _Char___init__impl__6a9atx(0);
          tmp$ret$2 = Char__toInt_impl_vasixd(tmp0__get_code__88qj9g);
          if (tmp1_Char < tmp$ret$2) {
            tmp_0 = true;
          } else {
            var tmp$ret$3;
            Companion_getInstance_18();
            var tmp1__get_code__adl84j = _Char___init__impl__6a9atx(65535);
            tmp$ret$3 = Char__toInt_impl_vasixd(tmp1__get_code__adl84j);
            tmp_0 = tmp1_Char > tmp$ret$3;
          }
          if (tmp_0) {
            throw IllegalArgumentException_init_$Create$_0("Invalid Char code: " + tmp1_Char);
          }
          tmp$ret$4 = numberToChar(tmp1_Char);
          tmp = tmp$ret$4;
        } else {
          tmp = a.get_a7b70_k$(index);
        }
        return tmp;
      }
      function isString2(a) {
        return typeof a === "string";
      }
      function charSequenceLength(a) {
        var tmp;
        if (isString2(a)) {
          var tmp$ret$1;
          var tmp$ret$0;
          tmp$ret$0 = a;
          var tmp0_unsafeCast = tmp$ret$0.length;
          tmp$ret$1 = tmp0_unsafeCast;
          tmp = tmp$ret$1;
        } else {
          tmp = a.get_length_g42xv3_k$();
        }
        return tmp;
      }
      function charSequenceSubSequence(a, startIndex, endIndex) {
        var tmp;
        if (isString2(a)) {
          var tmp$ret$1;
          var tmp$ret$0;
          tmp$ret$0 = a;
          var tmp0_unsafeCast = tmp$ret$0.substring(startIndex, endIndex);
          tmp$ret$1 = tmp0_unsafeCast;
          tmp = tmp$ret$1;
        } else {
          tmp = a.subSequence_5fh70h_k$(startIndex, endIndex);
        }
        return tmp;
      }
      function arrayToString(array3) {
        return joinToString$default(array3, ", ", "[", "]", 0, null, arrayToString$lambda, 24, null);
      }
      function contentEqualsInternal(_this__u8e3s4, other) {
        var tmp$ret$0;
        tmp$ret$0 = _this__u8e3s4;
        var a = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = other;
        var b = tmp$ret$1;
        if (a === b)
          return true;
        if (((a == null ? true : b == null) ? true : !isArrayish(b)) ? true : a.length != b.length)
          return false;
        var inductionVariable = 0;
        var last = a.length;
        if (inductionVariable < last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            if (!equals(a[i], b[i])) {
              return false;
            }
          } while (inductionVariable < last);
        return true;
      }
      function arrayToString$lambda(it) {
        return toString_1(it);
      }
      function compareTo_0(a, b) {
        var tmp0_subject = typeof a;
        var tmp;
        switch (tmp0_subject) {
          case "number":
            var tmp_0;
            if (typeof b === "number") {
              tmp_0 = doubleCompareTo(a, b);
            } else {
              if (b instanceof Long) {
                tmp_0 = doubleCompareTo(a, b.toDouble_ygsx0s_k$());
              } else {
                tmp_0 = primitiveCompareTo(a, b);
              }
            }
            tmp = tmp_0;
            break;
          case "string":
          case "boolean":
            tmp = primitiveCompareTo(a, b);
            break;
          default:
            tmp = compareToDoNotIntrinsicify(a, b);
            break;
        }
        return tmp;
      }
      function doubleCompareTo(a, b) {
        var tmp;
        if (a < b) {
          tmp = -1;
        } else if (a > b) {
          tmp = 1;
        } else if (a === b) {
          var tmp_0;
          if (a !== 0) {
            tmp_0 = 0;
          } else {
            var tmp$ret$0;
            tmp$ret$0 = 1;
            var ia = tmp$ret$0 / a;
            var tmp_1;
            var tmp$ret$1;
            tmp$ret$1 = 1;
            if (ia === tmp$ret$1 / b) {
              tmp_1 = 0;
            } else {
              if (ia < 0) {
                tmp_1 = -1;
              } else {
                tmp_1 = 1;
              }
            }
            tmp_0 = tmp_1;
          }
          tmp = tmp_0;
        } else if (a !== a) {
          tmp = b !== b ? 0 : 1;
        } else {
          tmp = -1;
        }
        return tmp;
      }
      function primitiveCompareTo(a, b) {
        return a < b ? -1 : a > b ? 1 : 0;
      }
      function compareToDoNotIntrinsicify(a, b) {
        return a.compareTo_6thzaj_k$(b);
      }
      function construct(constructorType, resultType, args) {
        return Reflect.construct(constructorType, args, resultType);
      }
      function identityHashCode(obj) {
        return getObjectHashCode(obj);
      }
      function getObjectHashCode(obj) {
        if (!jsIn("kotlinHashCodeValue$", obj)) {
          var hash2 = jsBitwiseOr(Math.random() * 4294967296, 0);
          var descriptor = new Object();
          descriptor.value = hash2;
          descriptor.enumerable = false;
          Object.defineProperty(obj, "kotlinHashCodeValue$", descriptor);
        }
        var tmp$ret$0;
        var tmp0_unsafeCast = obj["kotlinHashCodeValue$"];
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function get_OBJECT_HASH_CODE_PROPERTY_NAME() {
        return OBJECT_HASH_CODE_PROPERTY_NAME;
      }
      var OBJECT_HASH_CODE_PROPERTY_NAME;
      function get_POW_2_32() {
        return POW_2_32;
      }
      var POW_2_32;
      function toString_1(o) {
        var tmp;
        if (o == null) {
          tmp = "null";
        } else if (isArrayish(o)) {
          tmp = "[...]";
        } else {
          var tmp$ret$0;
          var tmp0_unsafeCast = o.toString();
          tmp$ret$0 = tmp0_unsafeCast;
          tmp = tmp$ret$0;
        }
        return tmp;
      }
      function hashCode(obj) {
        if (obj == null)
          return 0;
        var tmp0_subject = typeof obj;
        var tmp;
        switch (tmp0_subject) {
          case "object":
            tmp = "function" === typeof obj.hashCode ? obj.hashCode() : getObjectHashCode(obj);
            break;
          case "function":
            tmp = getObjectHashCode(obj);
            break;
          case "number":
            tmp = getNumberHashCode(obj);
            break;
          case "boolean":
            var tmp_0;
            var tmp$ret$0;
            tmp$ret$0 = obj;
            if (tmp$ret$0) {
              tmp_0 = 1;
            } else {
              tmp_0 = 0;
            }
            tmp = tmp_0;
            break;
          default:
            tmp = getStringHashCode(String(obj));
            break;
        }
        return tmp;
      }
      function getStringHashCode(str) {
        var hash2 = 0;
        var length = str.length;
        var inductionVariable = 0;
        var last = length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp$ret$0;
            tmp$ret$0 = str;
            var code = tmp$ret$0.charCodeAt(i);
            hash2 = imul(hash2, 31) + code | 0;
          } while (!(i === last));
        return hash2;
      }
      function anyToString(o) {
        return Object.prototype.toString.call(o);
      }
      function equals(obj1, obj2) {
        if (obj1 == null) {
          return obj2 == null;
        }
        if (obj2 == null) {
          return false;
        }
        if (typeof obj1 === "object" ? typeof obj1.equals === "function" : false) {
          return obj1.equals(obj2);
        }
        if (obj1 !== obj1) {
          return obj2 !== obj2;
        }
        if (typeof obj1 === "number" ? typeof obj2 === "number" : false) {
          var tmp;
          if (obj1 === obj2) {
            var tmp_0;
            if (obj1 !== 0) {
              tmp_0 = true;
            } else {
              var tmp$ret$0;
              tmp$ret$0 = 1;
              var tmp_1 = tmp$ret$0 / obj1;
              var tmp$ret$1;
              tmp$ret$1 = 1;
              tmp_0 = tmp_1 === tmp$ret$1 / obj2;
            }
            tmp = tmp_0;
          } else {
            tmp = false;
          }
          return tmp;
        }
        return obj1 === obj2;
      }
      function boxIntrinsic(x2) {
        throw IllegalStateException_init_$Create$_0("Should be lowered");
      }
      function unboxIntrinsic(x2) {
        throw IllegalStateException_init_$Create$_0("Should be lowered");
      }
      function captureStack(instance, constructorFunction) {
        if (Error.captureStackTrace != null) {
          Error.captureStackTrace(instance, constructorFunction);
        } else {
          var tmp$ret$0;
          tmp$ret$0 = instance;
          tmp$ret$0.stack = new Error().stack;
        }
      }
      function newThrowable(message, cause) {
        var throwable = new Error();
        var tmp;
        if (isUndefined2(message)) {
          var tmp_0;
          if (isUndefined2(cause)) {
            tmp_0 = message;
          } else {
            var tmp0_safe_receiver = cause;
            var tmp1_elvis_lhs = tmp0_safe_receiver == null ? null : tmp0_safe_receiver.toString();
            tmp_0 = tmp1_elvis_lhs == null ? void 0 : tmp1_elvis_lhs;
          }
          tmp = tmp_0;
        } else {
          var tmp2_elvis_lhs = message;
          tmp = tmp2_elvis_lhs == null ? void 0 : tmp2_elvis_lhs;
        }
        throwable.message = tmp;
        throwable.cause = cause;
        throwable.name = "Throwable";
        var tmp$ret$0;
        tmp$ret$0 = throwable;
        return tmp$ret$0;
      }
      function isUndefined2(value) {
        return value === void 0;
      }
      function extendThrowable(this_, message, cause) {
        Error.call(this_);
        setPropertiesToThrowableInstance(this_, message, cause);
      }
      function setPropertiesToThrowableInstance(this_, message, cause) {
        if (!hasOwnPrototypeProperty(this_, "message")) {
          var tmp;
          if (message == null) {
            var tmp_0;
            if (!(message === null)) {
              var tmp0_safe_receiver = cause;
              var tmp1_elvis_lhs = tmp0_safe_receiver == null ? null : tmp0_safe_receiver.toString();
              tmp_0 = tmp1_elvis_lhs == null ? void 0 : tmp1_elvis_lhs;
            } else {
              tmp_0 = void 0;
            }
            tmp = tmp_0;
          } else {
            tmp = message;
          }
          this_.message = tmp;
        }
        if (!hasOwnPrototypeProperty(this_, "cause")) {
          this_.cause = cause;
        }
        this_.name = Object.getPrototypeOf(this_).constructor.name;
      }
      function hasOwnPrototypeProperty(o, name) {
        var tmp$ret$0;
        var tmp0_unsafeCast = Object.getPrototypeOf(o).hasOwnProperty(name);
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function getContinuation() {
        throw Exception_init_$Create$_0("Implemented as intrinsic");
      }
      function returnIfSuspended(argument, $cont) {
        return (argument == null ? true : isObject3(argument)) ? argument : THROW_CCE();
      }
      function suspendCoroutineUninterceptedOrReturnJS(block, $cont) {
        return block($cont);
      }
      function getCoroutineContext($cont) {
        return $cont.get_context_h02k06_k$();
      }
      function unreachableDeclarationLog() {
        var tmp$ret$0;
        var tmp0_asDynamic = console;
        tmp$ret$0 = tmp0_asDynamic;
        tmp$ret$0.trace("Unreachable declaration");
      }
      function unreachableDeclarationException() {
        throw new Error("Unreachable declaration");
      }
      function ensureNotNull(v) {
        var tmp;
        if (v == null) {
          THROW_NPE();
        } else {
          tmp = v;
        }
        return tmp;
      }
      function THROW_NPE() {
        throw NullPointerException_init_$Create$();
      }
      function noWhenBranchMatchedException() {
        throw NoWhenBranchMatchedException_init_$Create$();
      }
      function THROW_CCE() {
        throw ClassCastException_init_$Create$();
      }
      function throwUninitializedPropertyAccessException(name) {
        throw UninitializedPropertyAccessException_init_$Create$_0("lateinit property " + name + " has not been initialized");
      }
      function throwKotlinNothingValueException() {
        throw KotlinNothingValueException_init_$Create$();
      }
      function THROW_ISE() {
        throw IllegalStateException_init_$Create$();
      }
      function THROW_IAE(msg) {
        throw IllegalArgumentException_init_$Create$_0(msg);
      }
      function JsIntrinsic() {
      }
      JsIntrinsic.prototype.equals = function(other) {
        if (!(other instanceof JsIntrinsic))
          return false;
        var tmp0_other_with_cast = other instanceof JsIntrinsic ? other : THROW_CCE();
        return true;
      };
      JsIntrinsic.prototype.hashCode = function() {
        return 0;
      };
      JsIntrinsic.prototype.toString = function() {
        return "@kotlin.js.JsIntrinsic()";
      };
      JsIntrinsic.$metadata$ = classMeta("JsIntrinsic", [Annotation]);
      function emptyArray() {
        return [];
      }
      function JsFun(code) {
        this.code_1 = code;
      }
      JsFun.prototype.get_code_wok7xy_k$ = function() {
        return this.code_1;
      };
      JsFun.prototype.equals = function(other) {
        if (!(other instanceof JsFun))
          return false;
        var tmp0_other_with_cast = other instanceof JsFun ? other : THROW_CCE();
        if (!(this.code_1 === tmp0_other_with_cast.code_1))
          return false;
        return true;
      };
      JsFun.prototype.hashCode = function() {
        return imul(getStringHashCode("code"), 127) ^ getStringHashCode(this.code_1);
      };
      JsFun.prototype.toString = function() {
        return "@kotlin.js.JsFun(code=" + this.code_1 + ")";
      };
      JsFun.$metadata$ = classMeta("JsFun", [Annotation]);
      function enumValueOfIntrinsic(name) {
        throw IllegalStateException_init_$Create$_0("Should be replaced by compiler");
      }
      function enumValuesIntrinsic() {
        throw IllegalStateException_init_$Create$_0("Should be replaced by compiler");
      }
      function Companion_20() {
        Companion_instance_20 = this;
        this.MIN_VALUE_1 = new Long(0, -2147483648);
        this.MAX_VALUE_1 = new Long(-1, 2147483647);
        this.SIZE_BYTES_1 = 8;
        this.SIZE_BITS_1 = 64;
      }
      Companion_20.prototype.get_MIN_VALUE_7nmmor_k$ = function() {
        return this.MIN_VALUE_1;
      };
      Companion_20.prototype.get_MAX_VALUE_54a9lf_k$ = function() {
        return this.MAX_VALUE_1;
      };
      Companion_20.prototype.get_SIZE_BYTES_qphg4q_k$ = function() {
        return this.SIZE_BYTES_1;
      };
      Companion_20.prototype.get_SIZE_BITS_7qhjj9_k$ = function() {
        return this.SIZE_BITS_1;
      };
      Companion_20.$metadata$ = objectMeta("Companion");
      var Companion_instance_20;
      function Companion_getInstance_20() {
        if (Companion_instance_20 == null)
          new Companion_20();
        return Companion_instance_20;
      }
      function Long(low, high) {
        Companion_getInstance_20();
        Number_0.call(this);
        this.low_1 = low;
        this.high_1 = high;
      }
      Long.prototype.get_low_18j191_k$ = function() {
        return this.low_1;
      };
      Long.prototype.get_high_wonai3_k$ = function() {
        return this.high_1;
      };
      Long.prototype.compareTo_n49k6u_k$ = function(other) {
        return this.compareTo_n4fqi2_k$(toLong(other));
      };
      Long.prototype.compareTo_6m5e4u_k$ = function(other) {
        return this.compareTo_n4fqi2_k$(toLong(other));
      };
      Long.prototype.compareTo_m60v27_k$ = function(other) {
        return this.compareTo_n4fqi2_k$(toLong(other));
      };
      Long.prototype.compareTo_n4fqi2_k$ = function(other) {
        return compare(this, other);
      };
      Long.prototype.compareTo_6thzaj_k$ = function(other) {
        return this.compareTo_n4fqi2_k$(other instanceof Long ? other : THROW_CCE());
      };
      Long.prototype.compareTo_6f2lym_k$ = function(other) {
        return compareTo_0(this.toFloat_jhbgwv_k$(), other);
      };
      Long.prototype.compareTo_f0f9kx_k$ = function(other) {
        return compareTo_0(this.toDouble_ygsx0s_k$(), other);
      };
      Long.prototype.plus_u6dpzk_k$ = function(other) {
        return this.plus_u6jwas_k$(toLong(other));
      };
      Long.prototype.plus_cce7xw_k$ = function(other) {
        return this.plus_u6jwas_k$(toLong(other));
      };
      Long.prototype.plus_crvk61_k$ = function(other) {
        return this.plus_u6jwas_k$(toLong(other));
      };
      Long.prototype.plus_u6jwas_k$ = function(other) {
        return add2(this, other);
      };
      Long.prototype.plus_c5bfro_k$ = function(other) {
        return this.toFloat_jhbgwv_k$() + other;
      };
      Long.prototype.plus_kiyahl_k$ = function(other) {
        return this.toDouble_ygsx0s_k$() + other;
      };
      Long.prototype.minus_ll8z3a_k$ = function(other) {
        return this.minus_llf5ei_k$(toLong(other));
      };
      Long.prototype.minus_u9ra1q_k$ = function(other) {
        return this.minus_llf5ei_k$(toLong(other));
      };
      Long.prototype.minus_c5ihzl_k$ = function(other) {
        return this.minus_llf5ei_k$(toLong(other));
      };
      Long.prototype.minus_llf5ei_k$ = function(other) {
        return subtract(this, other);
      };
      Long.prototype.minus_u2ohvi_k$ = function(other) {
        return this.toFloat_jhbgwv_k$() - other;
      };
      Long.prototype.minus_80anzj_k$ = function(other) {
        return this.toDouble_ygsx0s_k$() - other;
      };
      Long.prototype.times_2z9ke4_k$ = function(other) {
        return this.times_2zfqpc_k$(toLong(other));
      };
      Long.prototype.times_ll626g_k$ = function(other) {
        return this.times_2zfqpc_k$(toLong(other));
      };
      Long.prototype.times_vzczyd_k$ = function(other) {
        return this.times_2zfqpc_k$(toLong(other));
      };
      Long.prototype.times_2zfqpc_k$ = function(other) {
        return multiply(this, other);
      };
      Long.prototype.times_le3a08_k$ = function(other) {
        return this.toFloat_jhbgwv_k$() * other;
      };
      Long.prototype.times_myh3yd_k$ = function(other) {
        return this.toDouble_ygsx0s_k$() * other;
      };
      Long.prototype.div_9rv96v_k$ = function(other) {
        return this.div_9s1fi3_k$(toLong(other));
      };
      Long.prototype.div_j4i90d_k$ = function(other) {
        return this.div_9s1fi3_k$(toLong(other));
      };
      Long.prototype.div_pipt5c_k$ = function(other) {
        return this.div_9s1fi3_k$(toLong(other));
      };
      Long.prototype.div_9s1fi3_k$ = function(other) {
        return divide(this, other);
      };
      Long.prototype.div_ixfgu5_k$ = function(other) {
        return this.toFloat_jhbgwv_k$() / other;
      };
      Long.prototype.div_hn31ow_k$ = function(other) {
        return this.toDouble_ygsx0s_k$() / other;
      };
      Long.prototype.rem_9r568g_k$ = function(other) {
        return this.rem_9rbcjo_k$(toLong(other));
      };
      Long.prototype.rem_ii1pdg_k$ = function(other) {
        return this.rem_9rbcjo_k$(toLong(other));
      };
      Long.prototype.rem_kb2195_k$ = function(other) {
        return this.rem_9rbcjo_k$(toLong(other));
      };
      Long.prototype.rem_9rbcjo_k$ = function(other) {
        return modulo(this, other);
      };
      Long.prototype.rem_iayx78_k$ = function(other) {
        return this.toFloat_jhbgwv_k$() % other;
      };
      Long.prototype.rem_1p5v1j_k$ = function(other) {
        return this.toDouble_ygsx0s_k$() % other;
      };
      Long.prototype.inc_28ke_k$ = function() {
        return this.plus_u6jwas_k$(new Long(1, 0));
      };
      Long.prototype.dec_24n6_k$ = function() {
        return this.minus_llf5ei_k$(new Long(1, 0));
      };
      Long.prototype.unaryPlus_g9fn1l_k$ = function() {
        return this;
      };
      Long.prototype.unaryMinus_6uz0qp_k$ = function() {
        return this.inv_28kx_k$().plus_u6jwas_k$(new Long(1, 0));
      };
      Long.prototype.rangeTo_5ifbqq_k$ = function(other) {
        return this.rangeTo_5i95fi_k$(toLong(other));
      };
      Long.prototype.rangeTo_sjxg22_k$ = function(other) {
        return this.rangeTo_5i95fi_k$(toLong(other));
      };
      Long.prototype.rangeTo_pdrcev_k$ = function(other) {
        return this.rangeTo_5i95fi_k$(toLong(other));
      };
      Long.prototype.rangeTo_5i95fi_k$ = function(other) {
        return new LongRange(this, other);
      };
      Long.prototype.shl_po5ip6_k$ = function(bitCount) {
        return shiftLeft(this, bitCount);
      };
      Long.prototype.shr_wjue3g_k$ = function(bitCount) {
        return shiftRight(this, bitCount);
      };
      Long.prototype.ushr_rr8rvr_k$ = function(bitCount) {
        return shiftRightUnsigned(this, bitCount);
      };
      Long.prototype.and_jhajnj_k$ = function(other) {
        return new Long(this.low_1 & other.low_1, this.high_1 & other.high_1);
      };
      Long.prototype.or_s401rn_k$ = function(other) {
        return new Long(this.low_1 | other.low_1, this.high_1 | other.high_1);
      };
      Long.prototype.xor_jjua9n_k$ = function(other) {
        return new Long(this.low_1 ^ other.low_1, this.high_1 ^ other.high_1);
      };
      Long.prototype.inv_28kx_k$ = function() {
        return new Long(~this.low_1, ~this.high_1);
      };
      Long.prototype.toByte_edm0nx_k$ = function() {
        return toByte(this.low_1);
      };
      Long.prototype.toChar_tbflse_k$ = function() {
        return numberToChar(this.low_1);
      };
      Long.prototype.toShort_ja8oqn_k$ = function() {
        return toShort(this.low_1);
      };
      Long.prototype.toInt_1tsl84_k$ = function() {
        return this.low_1;
      };
      Long.prototype.toLong_edfucp_k$ = function() {
        return this;
      };
      Long.prototype.toFloat_jhbgwv_k$ = function() {
        return this.toDouble_ygsx0s_k$();
      };
      Long.prototype.toDouble_ygsx0s_k$ = function() {
        return toNumber(this);
      };
      Long.prototype.valueOf = function() {
        return this.toDouble_ygsx0s_k$();
      };
      Long.prototype.equals = function(other) {
        var tmp;
        if (other instanceof Long) {
          tmp = equalsLong(this, other);
        } else {
          tmp = false;
        }
        return tmp;
      };
      Long.prototype.hashCode = function() {
        return hashCode_0(this);
      };
      Long.prototype.toString = function() {
        return toStringImpl(this, 10);
      };
      Long.$metadata$ = classMeta("Long", [Comparable], void 0, void 0, void 0, Number_0.prototype);
      function get_ZERO() {
        init_properties_longjs_kt_ttk8rv();
        return ZERO;
      }
      var ZERO;
      function get_ONE() {
        init_properties_longjs_kt_ttk8rv();
        return ONE;
      }
      var ONE;
      function get_NEG_ONE() {
        init_properties_longjs_kt_ttk8rv();
        return NEG_ONE;
      }
      var NEG_ONE;
      function get_MAX_VALUE() {
        init_properties_longjs_kt_ttk8rv();
        return MAX_VALUE;
      }
      var MAX_VALUE;
      function get_MIN_VALUE() {
        init_properties_longjs_kt_ttk8rv();
        return MIN_VALUE;
      }
      var MIN_VALUE;
      function get_TWO_PWR_24_() {
        init_properties_longjs_kt_ttk8rv();
        return TWO_PWR_24_;
      }
      var TWO_PWR_24_;
      function compare(_this__u8e3s4, other) {
        init_properties_longjs_kt_ttk8rv();
        if (equalsLong(_this__u8e3s4, other)) {
          return 0;
        }
        var thisNeg = isNegative(_this__u8e3s4);
        var otherNeg = isNegative(other);
        return (thisNeg ? !otherNeg : false) ? -1 : (!thisNeg ? otherNeg : false) ? 1 : isNegative(subtract(_this__u8e3s4, other)) ? -1 : 1;
      }
      function add2(_this__u8e3s4, other) {
        init_properties_longjs_kt_ttk8rv();
        var a48 = _this__u8e3s4.high_1 >>> 16 | 0;
        var a32 = _this__u8e3s4.high_1 & 65535;
        var a16 = _this__u8e3s4.low_1 >>> 16 | 0;
        var a00 = _this__u8e3s4.low_1 & 65535;
        var b48 = other.high_1 >>> 16 | 0;
        var b32 = other.high_1 & 65535;
        var b16 = other.low_1 >>> 16 | 0;
        var b00 = other.low_1 & 65535;
        var c48 = 0;
        var c32 = 0;
        var c16 = 0;
        var c00 = 0;
        c00 = c00 + (a00 + b00 | 0) | 0;
        c16 = c16 + (c00 >>> 16 | 0) | 0;
        c00 = c00 & 65535;
        c16 = c16 + (a16 + b16 | 0) | 0;
        c32 = c32 + (c16 >>> 16 | 0) | 0;
        c16 = c16 & 65535;
        c32 = c32 + (a32 + b32 | 0) | 0;
        c48 = c48 + (c32 >>> 16 | 0) | 0;
        c32 = c32 & 65535;
        c48 = c48 + (a48 + b48 | 0) | 0;
        c48 = c48 & 65535;
        return new Long(c16 << 16 | c00, c48 << 16 | c32);
      }
      function subtract(_this__u8e3s4, other) {
        init_properties_longjs_kt_ttk8rv();
        return add2(_this__u8e3s4, other.unaryMinus_6uz0qp_k$());
      }
      function multiply(_this__u8e3s4, other) {
        init_properties_longjs_kt_ttk8rv();
        if (isZero(_this__u8e3s4)) {
          return get_ZERO();
        } else if (isZero(other)) {
          return get_ZERO();
        }
        if (equalsLong(_this__u8e3s4, get_MIN_VALUE())) {
          return isOdd(other) ? get_MIN_VALUE() : get_ZERO();
        } else if (equalsLong(other, get_MIN_VALUE())) {
          return isOdd(_this__u8e3s4) ? get_MIN_VALUE() : get_ZERO();
        }
        if (isNegative(_this__u8e3s4)) {
          var tmp;
          if (isNegative(other)) {
            tmp = multiply(negate(_this__u8e3s4), negate(other));
          } else {
            tmp = negate(multiply(negate(_this__u8e3s4), other));
          }
          return tmp;
        } else if (isNegative(other)) {
          return negate(multiply(_this__u8e3s4, negate(other)));
        }
        if (lessThan(_this__u8e3s4, get_TWO_PWR_24_()) ? lessThan(other, get_TWO_PWR_24_()) : false) {
          return fromNumber(toNumber(_this__u8e3s4) * toNumber(other));
        }
        var a48 = _this__u8e3s4.high_1 >>> 16 | 0;
        var a32 = _this__u8e3s4.high_1 & 65535;
        var a16 = _this__u8e3s4.low_1 >>> 16 | 0;
        var a00 = _this__u8e3s4.low_1 & 65535;
        var b48 = other.high_1 >>> 16 | 0;
        var b32 = other.high_1 & 65535;
        var b16 = other.low_1 >>> 16 | 0;
        var b00 = other.low_1 & 65535;
        var c48 = 0;
        var c32 = 0;
        var c16 = 0;
        var c00 = 0;
        c00 = c00 + imul(a00, b00) | 0;
        c16 = c16 + (c00 >>> 16 | 0) | 0;
        c00 = c00 & 65535;
        c16 = c16 + imul(a16, b00) | 0;
        c32 = c32 + (c16 >>> 16 | 0) | 0;
        c16 = c16 & 65535;
        c16 = c16 + imul(a00, b16) | 0;
        c32 = c32 + (c16 >>> 16 | 0) | 0;
        c16 = c16 & 65535;
        c32 = c32 + imul(a32, b00) | 0;
        c48 = c48 + (c32 >>> 16 | 0) | 0;
        c32 = c32 & 65535;
        c32 = c32 + imul(a16, b16) | 0;
        c48 = c48 + (c32 >>> 16 | 0) | 0;
        c32 = c32 & 65535;
        c32 = c32 + imul(a00, b32) | 0;
        c48 = c48 + (c32 >>> 16 | 0) | 0;
        c32 = c32 & 65535;
        c48 = c48 + (((imul(a48, b00) + imul(a32, b16) | 0) + imul(a16, b32) | 0) + imul(a00, b48) | 0) | 0;
        c48 = c48 & 65535;
        return new Long(c16 << 16 | c00, c48 << 16 | c32);
      }
      function divide(_this__u8e3s4, other) {
        init_properties_longjs_kt_ttk8rv();
        if (isZero(other)) {
          throw Exception_init_$Create$_0("division by zero");
        } else if (isZero(_this__u8e3s4)) {
          return get_ZERO();
        }
        if (equalsLong(_this__u8e3s4, get_MIN_VALUE())) {
          if (equalsLong(other, get_ONE()) ? true : equalsLong(other, get_NEG_ONE())) {
            return get_MIN_VALUE();
          } else if (equalsLong(other, get_MIN_VALUE())) {
            return get_ONE();
          } else {
            var halfThis = shiftRight(_this__u8e3s4, 1);
            var approx = shiftLeft(halfThis.div_9s1fi3_k$(other), 1);
            if (equalsLong(approx, get_ZERO())) {
              return isNegative(other) ? get_ONE() : get_NEG_ONE();
            } else {
              var rem = subtract(_this__u8e3s4, multiply(other, approx));
              return add2(approx, rem.div_9s1fi3_k$(other));
            }
          }
        } else if (equalsLong(other, get_MIN_VALUE())) {
          return get_ZERO();
        }
        if (isNegative(_this__u8e3s4)) {
          var tmp;
          if (isNegative(other)) {
            tmp = negate(_this__u8e3s4).div_9s1fi3_k$(negate(other));
          } else {
            tmp = negate(negate(_this__u8e3s4).div_9s1fi3_k$(other));
          }
          return tmp;
        } else if (isNegative(other)) {
          return negate(_this__u8e3s4.div_9s1fi3_k$(negate(other)));
        }
        var res = get_ZERO();
        var rem_0 = _this__u8e3s4;
        while (greaterThanOrEqual(rem_0, other)) {
          var approxDouble = toNumber(rem_0) / toNumber(other);
          var approx2 = Math.max(1, Math.floor(approxDouble));
          var log22 = Math.ceil(Math.log(approx2) / Math.LN2);
          var delta = log22 <= 48 ? 1 : Math.pow(2, log22 - 48);
          var approxRes = fromNumber(approx2);
          var approxRem = multiply(approxRes, other);
          while (isNegative(approxRem) ? true : greaterThan(approxRem, rem_0)) {
            approx2 = approx2 - delta;
            approxRes = fromNumber(approx2);
            approxRem = multiply(approxRes, other);
          }
          if (isZero(approxRes)) {
            approxRes = get_ONE();
          }
          res = add2(res, approxRes);
          rem_0 = subtract(rem_0, approxRem);
        }
        return res;
      }
      function modulo(_this__u8e3s4, other) {
        init_properties_longjs_kt_ttk8rv();
        return subtract(_this__u8e3s4, multiply(_this__u8e3s4.div_9s1fi3_k$(other), other));
      }
      function shiftLeft(_this__u8e3s4, numBits) {
        init_properties_longjs_kt_ttk8rv();
        var numBits_0 = numBits & 63;
        if (numBits_0 === 0) {
          return _this__u8e3s4;
        } else {
          if (numBits_0 < 32) {
            return new Long(_this__u8e3s4.low_1 << numBits_0, _this__u8e3s4.high_1 << numBits_0 | (_this__u8e3s4.low_1 >>> (32 - numBits_0 | 0) | 0));
          } else {
            return new Long(0, _this__u8e3s4.low_1 << (numBits_0 - 32 | 0));
          }
        }
      }
      function shiftRight(_this__u8e3s4, numBits) {
        init_properties_longjs_kt_ttk8rv();
        var numBits_0 = numBits & 63;
        if (numBits_0 === 0) {
          return _this__u8e3s4;
        } else {
          if (numBits_0 < 32) {
            return new Long(_this__u8e3s4.low_1 >>> numBits_0 | 0 | _this__u8e3s4.high_1 << (32 - numBits_0 | 0), _this__u8e3s4.high_1 >> numBits_0);
          } else {
            return new Long(_this__u8e3s4.high_1 >> (numBits_0 - 32 | 0), _this__u8e3s4.high_1 >= 0 ? 0 : -1);
          }
        }
      }
      function shiftRightUnsigned(_this__u8e3s4, numBits) {
        init_properties_longjs_kt_ttk8rv();
        var numBits_0 = numBits & 63;
        if (numBits_0 === 0) {
          return _this__u8e3s4;
        } else {
          if (numBits_0 < 32) {
            return new Long(_this__u8e3s4.low_1 >>> numBits_0 | 0 | _this__u8e3s4.high_1 << (32 - numBits_0 | 0), _this__u8e3s4.high_1 >>> numBits_0 | 0);
          } else {
            var tmp;
            if (numBits_0 === 32) {
              tmp = new Long(_this__u8e3s4.high_1, 0);
            } else {
              tmp = new Long(_this__u8e3s4.high_1 >>> (numBits_0 - 32 | 0) | 0, 0);
            }
            return tmp;
          }
        }
      }
      function toNumber(_this__u8e3s4) {
        init_properties_longjs_kt_ttk8rv();
        return _this__u8e3s4.high_1 * 4294967296 + getLowBitsUnsigned(_this__u8e3s4);
      }
      function equalsLong(_this__u8e3s4, other) {
        init_properties_longjs_kt_ttk8rv();
        return _this__u8e3s4.high_1 === other.high_1 ? _this__u8e3s4.low_1 === other.low_1 : false;
      }
      function hashCode_0(l2) {
        init_properties_longjs_kt_ttk8rv();
        return l2.low_1 ^ l2.high_1;
      }
      function toStringImpl(_this__u8e3s4, radix) {
        init_properties_longjs_kt_ttk8rv();
        if (radix < 2 ? true : 36 < radix) {
          throw Exception_init_$Create$_0("radix out of range: " + radix);
        }
        if (isZero(_this__u8e3s4)) {
          return "0";
        }
        if (isNegative(_this__u8e3s4)) {
          if (equalsLong(_this__u8e3s4, get_MIN_VALUE())) {
            var radixLong = fromInt(radix);
            var div = _this__u8e3s4.div_9s1fi3_k$(radixLong);
            var rem = subtract(multiply(div, radixLong), _this__u8e3s4).toInt_1tsl84_k$();
            var tmp = toStringImpl(div, radix);
            var tmp$ret$1;
            var tmp$ret$0;
            tmp$ret$0 = rem;
            var tmp0_unsafeCast = tmp$ret$0.toString(radix);
            tmp$ret$1 = tmp0_unsafeCast;
            return tmp + tmp$ret$1;
          } else {
            return "-" + toStringImpl(negate(_this__u8e3s4), radix);
          }
        }
        var digitsPerTime = radix === 2 ? 31 : radix <= 10 ? 9 : radix <= 21 ? 7 : radix <= 35 ? 6 : 5;
        var radixToPower = fromNumber(Math.pow(radix, digitsPerTime));
        var rem_0 = _this__u8e3s4;
        var result = "";
        while (true) {
          var remDiv = rem_0.div_9s1fi3_k$(radixToPower);
          var intval = subtract(rem_0, multiply(remDiv, radixToPower)).toInt_1tsl84_k$();
          var tmp$ret$3;
          var tmp$ret$2;
          tmp$ret$2 = intval;
          var tmp1_unsafeCast = tmp$ret$2.toString(radix);
          tmp$ret$3 = tmp1_unsafeCast;
          var digits = tmp$ret$3;
          rem_0 = remDiv;
          if (isZero(rem_0)) {
            return digits + result;
          } else {
            while (digits.length < digitsPerTime) {
              digits = "0" + digits;
            }
            result = digits + result;
          }
        }
      }
      function fromInt(value) {
        init_properties_longjs_kt_ttk8rv();
        return new Long(value, value < 0 ? -1 : 0);
      }
      function isNegative(_this__u8e3s4) {
        init_properties_longjs_kt_ttk8rv();
        return _this__u8e3s4.high_1 < 0;
      }
      function isZero(_this__u8e3s4) {
        init_properties_longjs_kt_ttk8rv();
        return _this__u8e3s4.high_1 === 0 ? _this__u8e3s4.low_1 === 0 : false;
      }
      function isOdd(_this__u8e3s4) {
        init_properties_longjs_kt_ttk8rv();
        return (_this__u8e3s4.low_1 & 1) === 1;
      }
      function negate(_this__u8e3s4) {
        init_properties_longjs_kt_ttk8rv();
        return _this__u8e3s4.unaryMinus_6uz0qp_k$();
      }
      function lessThan(_this__u8e3s4, other) {
        init_properties_longjs_kt_ttk8rv();
        return compare(_this__u8e3s4, other) < 0;
      }
      function fromNumber(value) {
        init_properties_longjs_kt_ttk8rv();
        if (isNaN_0(value)) {
          return get_ZERO();
        } else if (value <= -9223372036854776e3) {
          return get_MIN_VALUE();
        } else if (value + 1 >= 9223372036854776e3) {
          return get_MAX_VALUE();
        } else if (value < 0) {
          return negate(fromNumber(-value));
        } else {
          var twoPwr32 = 4294967296;
          return new Long(jsBitwiseOr(value % twoPwr32, 0), jsBitwiseOr(value / twoPwr32, 0));
        }
      }
      function greaterThan(_this__u8e3s4, other) {
        init_properties_longjs_kt_ttk8rv();
        return compare(_this__u8e3s4, other) > 0;
      }
      function greaterThanOrEqual(_this__u8e3s4, other) {
        init_properties_longjs_kt_ttk8rv();
        return compare(_this__u8e3s4, other) >= 0;
      }
      function getLowBitsUnsigned(_this__u8e3s4) {
        init_properties_longjs_kt_ttk8rv();
        return _this__u8e3s4.low_1 >= 0 ? _this__u8e3s4.low_1 : 4294967296 + _this__u8e3s4.low_1;
      }
      function get_TWO_PWR_32_DBL_() {
        return TWO_PWR_32_DBL_;
      }
      var TWO_PWR_32_DBL_;
      function get_TWO_PWR_63_DBL_() {
        return TWO_PWR_63_DBL_;
      }
      var TWO_PWR_63_DBL_;
      var properties_initialized_longjs_kt_5aju7t;
      function init_properties_longjs_kt_ttk8rv() {
        if (properties_initialized_longjs_kt_5aju7t) {
        } else {
          properties_initialized_longjs_kt_5aju7t = true;
          ZERO = fromInt(0);
          ONE = fromInt(1);
          NEG_ONE = fromInt(-1);
          MAX_VALUE = new Long(-1, 2147483647);
          MIN_VALUE = new Long(0, -2147483648);
          TWO_PWR_24_ = fromInt(16777216);
        }
      }
      function withType(type, array3) {
        array3.$type$ = type;
        return array3;
      }
      function arrayConcat(args) {
        var len = args.length;
        var tmp$ret$0;
        var tmp0_unsafeCast = Array(len);
        tmp$ret$0 = tmp0_unsafeCast;
        var typed = tmp$ret$0;
        var inductionVariable = 0;
        var last = len - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var arr = args[i];
            if (!(!(arr == null) ? isArray(arr) : false)) {
              typed[i] = [].slice.call(arr);
            } else {
              typed[i] = arr;
            }
          } while (!(i === last));
        return [].concat.apply([], typed);
      }
      function primitiveArrayConcat(args) {
        var size_local = 0;
        var inductionVariable = 0;
        var last = args.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp = size_local;
            var tmp$ret$1;
            var tmp0_unsafeCast = args[i];
            var tmp$ret$0;
            tmp$ret$0 = tmp0_unsafeCast;
            tmp$ret$1 = tmp$ret$0;
            size_local = tmp + tmp$ret$1.length | 0;
          } while (!(i === last));
        var a = args[0];
        var tmp$ret$2;
        var tmp1_unsafeCast = new a.constructor(size_local);
        tmp$ret$2 = tmp1_unsafeCast;
        var result = tmp$ret$2;
        var tmp$ret$3;
        tmp$ret$3 = a;
        if (tmp$ret$3.$type$ != null) {
          var tmp$ret$5;
          var tmp$ret$4;
          tmp$ret$4 = a;
          var tmp2_withType = tmp$ret$4.$type$;
          result.$type$ = tmp2_withType;
          tmp$ret$5 = result;
        }
        size_local = 0;
        var inductionVariable_0 = 0;
        var last_0 = args.length - 1 | 0;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var tmp$ret$7;
            var tmp3_unsafeCast = args[i_0];
            var tmp$ret$6;
            tmp$ret$6 = tmp3_unsafeCast;
            tmp$ret$7 = tmp$ret$6;
            var arr = tmp$ret$7;
            var inductionVariable_1 = 0;
            var last_1 = arr.length - 1 | 0;
            if (inductionVariable_1 <= last_1)
              do {
                var j = inductionVariable_1;
                inductionVariable_1 = inductionVariable_1 + 1 | 0;
                var tmp3 = size_local;
                size_local = tmp3 + 1 | 0;
                result[tmp3] = arr[j];
              } while (!(j === last_1));
          } while (!(i_0 === last_0));
        var tmp$ret$9;
        var tmp$ret$8;
        tmp$ret$8 = result;
        tmp$ret$9 = tmp$ret$8;
        return tmp$ret$9;
      }
      function taggedArrayCopy(array3) {
        var res = array3.slice();
        res.$type$ = array3.$type$;
        var tmp$ret$0;
        tmp$ret$0 = res;
        return tmp$ret$0;
      }
      function numberToByte(a) {
        return toByte(numberToInt(a));
      }
      function toByte(a) {
        var tmp$ret$0;
        var tmp0_unsafeCast = a << 24 >> 24;
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function numberToInt(a) {
        var tmp;
        if (a instanceof Long) {
          tmp = a.toInt_1tsl84_k$();
        } else {
          tmp = doubleToInt(a);
        }
        return tmp;
      }
      function doubleToInt(a) {
        return a > 2147483647 ? 2147483647 : a < -2147483648 ? -2147483648 : jsBitwiseOr(a, 0);
      }
      function numberToDouble(a) {
        var tmp$ret$0;
        var tmp0_unsafeCast = +a;
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function numberToShort(a) {
        return toShort(numberToInt(a));
      }
      function toShort(a) {
        var tmp$ret$0;
        var tmp0_unsafeCast = a << 16 >> 16;
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function numberToLong(a) {
        var tmp;
        if (a instanceof Long) {
          tmp = a;
        } else {
          tmp = fromNumber(a);
        }
        return tmp;
      }
      function numberToChar(a) {
        var tmp$ret$0;
        var tmp0_toUShort = numberToInt(a);
        tmp$ret$0 = _UShort___init__impl__jigrne(toShort(tmp0_toUShort));
        return _Char___init__impl__6a9atx_0(tmp$ret$0);
      }
      function toLong(a) {
        return fromInt(a);
      }
      function numberRangeToNumber(start2, endInclusive) {
        return new IntRange(start2, endInclusive);
      }
      function numberRangeToLong(start2, endInclusive) {
        return new LongRange(numberToLong(start2), endInclusive);
      }
      function get_propertyRefClassMetadataCache() {
        init_properties_reflectRuntime_kt_yf9l8h();
        return propertyRefClassMetadataCache;
      }
      var propertyRefClassMetadataCache;
      function metadataObject() {
        init_properties_reflectRuntime_kt_yf9l8h();
        var undef = void 0;
        return classMeta(undef, undef, undef, undef, undef, undef);
      }
      function getPropertyCallableRef(name, paramCount, type, getter, setter) {
        init_properties_reflectRuntime_kt_yf9l8h();
        getter.get = getter;
        getter.set = setter;
        getter.callableName = name;
        var tmp$ret$0;
        var tmp0_unsafeCast = getPropertyRefClass(getter, getKPropMetadata(paramCount, setter, type));
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function getPropertyRefClass(obj, metadata) {
        init_properties_reflectRuntime_kt_yf9l8h();
        obj.$metadata$ = metadata;
        obj.constructor = obj;
        return obj;
      }
      function getKPropMetadata(paramCount, setter, type) {
        init_properties_reflectRuntime_kt_yf9l8h();
        var mdata = get_propertyRefClassMetadataCache()[paramCount][setter == null ? 0 : 1];
        if (mdata.interfaces.length === 0) {
          var tmp$ret$0;
          var tmp0_asDynamic = mdata.interfaces;
          tmp$ret$0 = tmp0_asDynamic;
          tmp$ret$0.push(type);
          if (mdata.interfacesCache == null) {
            mdata.interfacesCache = generateInterfaceCache();
          } else {
            ensureNotNull(mdata.interfacesCache).isComplete = false;
          }
          extendCacheWithSingle(ensureNotNull(mdata.interfacesCache), type);
        }
        return mdata;
      }
      function getLocalDelegateReference(name, type, mutable, lambda) {
        init_properties_reflectRuntime_kt_yf9l8h();
        return getPropertyCallableRef(name, 0, type, lambda, mutable ? lambda : null);
      }
      var properties_initialized_reflectRuntime_kt_inkhwd;
      function init_properties_reflectRuntime_kt_yf9l8h() {
        if (properties_initialized_reflectRuntime_kt_inkhwd) {
        } else {
          properties_initialized_reflectRuntime_kt_inkhwd = true;
          var tmp$ret$11;
          var tmp$ret$2;
          var tmp0_arrayOf = [metadataObject(), metadataObject()];
          var tmp$ret$1;
          var tmp$ret$0;
          tmp$ret$0 = tmp0_arrayOf;
          tmp$ret$1 = tmp$ret$0;
          tmp$ret$2 = tmp$ret$1;
          var tmp = tmp$ret$2;
          var tmp$ret$5;
          var tmp1_arrayOf = [metadataObject(), metadataObject()];
          var tmp$ret$4;
          var tmp$ret$3;
          tmp$ret$3 = tmp1_arrayOf;
          tmp$ret$4 = tmp$ret$3;
          tmp$ret$5 = tmp$ret$4;
          var tmp_0 = tmp$ret$5;
          var tmp$ret$8;
          var tmp2_arrayOf = [metadataObject(), metadataObject()];
          var tmp$ret$7;
          var tmp$ret$6;
          tmp$ret$6 = tmp2_arrayOf;
          tmp$ret$7 = tmp$ret$6;
          tmp$ret$8 = tmp$ret$7;
          var tmp3_arrayOf = [tmp, tmp_0, tmp$ret$8];
          var tmp$ret$10;
          var tmp$ret$9;
          tmp$ret$9 = tmp3_arrayOf;
          tmp$ret$10 = tmp$ret$9;
          tmp$ret$11 = tmp$ret$10;
          propertyRefClassMetadataCache = tmp$ret$11;
        }
      }
      function set_interfacesCounter(_set____db54di) {
        interfacesCounter = _set____db54di;
      }
      function get_interfacesCounter() {
        return interfacesCounter;
      }
      var interfacesCounter;
      function classMeta(name, interfaces, associatedObjectKey, associatedObjects, suspendArity, fastPrototype) {
        return createMetadata("class", name, interfaces, associatedObjectKey, associatedObjects, suspendArity, fastPrototype);
      }
      function createMetadata(kind, name, interfaces, associatedObjectKey, associatedObjects, suspendArity, fastPrototype) {
        return { kind, simpleName: name, interfaceId: kind === "interface" ? -1 : void 0, interfaces: interfaces || [], associatedObjectKey, associatedObjects, suspendArity, fastPrototype, $kClass$: void 0, interfacesCache: { isComplete: fastPrototype === void 0 && (interfaces === void 0 || interfaces.length === 0), implementInterfaceMemo: {} } };
      }
      function isArrayish(o) {
        return isJsArray(o) ? true : isView(o);
      }
      function isJsArray(obj) {
        var tmp$ret$0;
        var tmp0_unsafeCast = Array.isArray(obj);
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function isInterface(obj, iface) {
        var tmp0_elvis_lhs = obj.constructor;
        var tmp;
        if (tmp0_elvis_lhs == null) {
          return false;
        } else {
          tmp = tmp0_elvis_lhs;
        }
        var ctor = tmp;
        return isInterfaceImpl(ctor, iface);
      }
      function isInterfaceImpl(ctor, iface) {
        if (ctor === iface) {
          return true;
        }
        var metadata = ctor.$metadata$;
        if (!(metadata == null) ? metadata.interfacesCache == null : false) {
          metadata.interfacesCache = generateInterfaceCache();
        }
        var tmp0_safe_receiver = metadata;
        var interfacesCache = tmp0_safe_receiver == null ? null : tmp0_safe_receiver.interfacesCache;
        var tmp;
        if (!(interfacesCache == null)) {
          if (!interfacesCache.isComplete) {
            completeInterfaceCache(ctor);
          }
          var tmp1_safe_receiver = iface.$metadata$;
          var tmp2_elvis_lhs = tmp1_safe_receiver == null ? null : tmp1_safe_receiver.interfaceId;
          var tmp_0;
          if (tmp2_elvis_lhs == null) {
            return false;
          } else {
            tmp_0 = tmp2_elvis_lhs;
          }
          var interfaceId = tmp_0;
          tmp = !!interfacesCache.implementInterfaceMemo[interfaceId];
        } else {
          var tmp3_safe_receiver = fastGetPrototype(ctor);
          var tmp4_elvis_lhs = tmp3_safe_receiver == null ? null : tmp3_safe_receiver.constructor;
          var tmp_1;
          if (tmp4_elvis_lhs == null) {
            return false;
          } else {
            tmp_1 = tmp4_elvis_lhs;
          }
          var constructor = tmp_1;
          tmp = isInterfaceImpl(constructor, iface);
        }
        return tmp;
      }
      function generateInterfaceCache() {
        return { isComplete: false, implementInterfaceMemo: {} };
      }
      function completeInterfaceCache(ctor) {
        var metadata = ctor.$metadata$;
        if (!(metadata == null) ? metadata.interfacesCache == null : false) {
          metadata.interfacesCache = generateInterfaceCache();
        }
        var tmp0_safe_receiver = metadata;
        var interfacesCache = tmp0_safe_receiver == null ? null : tmp0_safe_receiver.interfacesCache;
        if (!(interfacesCache == null)) {
          if (interfacesCache.isComplete === true) {
            return interfacesCache;
          }
          var indexedObject = metadata.interfaces;
          var inductionVariable = 0;
          var last = indexedObject.length;
          while (inductionVariable < last) {
            var i = indexedObject[inductionVariable];
            inductionVariable = inductionVariable + 1 | 0;
            extendCacheWithSingle(interfacesCache, i);
            extendCacheWith(interfacesCache, completeInterfaceCache(i));
          }
        }
        var tmp2_safe_receiver = fastGetPrototype(ctor);
        var tmp3_safe_receiver = tmp2_safe_receiver == null ? null : tmp2_safe_receiver.constructor;
        var tmp;
        if (tmp3_safe_receiver == null) {
          tmp = null;
        } else {
          var tmp$ret$0;
          tmp$ret$0 = completeInterfaceCache(tmp3_safe_receiver);
          tmp = tmp$ret$0;
        }
        var parentInterfacesCache = tmp;
        var tmp4_safe_receiver = interfacesCache;
        var tmp_0;
        if (tmp4_safe_receiver == null) {
          tmp_0 = null;
        } else {
          var tmp$ret$1;
          extendCacheWith(tmp4_safe_receiver, parentInterfacesCache);
          tmp4_safe_receiver.isComplete = true;
          tmp$ret$1 = tmp4_safe_receiver;
          tmp_0 = tmp$ret$1;
        }
        var tmp5_elvis_lhs = tmp_0;
        return tmp5_elvis_lhs == null ? parentInterfacesCache : tmp5_elvis_lhs;
      }
      function fastGetPrototype(ctor) {
        var tmp0_safe_receiver = ctor.$metadata$;
        var tmp;
        if (tmp0_safe_receiver == null) {
          tmp = null;
        } else {
          var tmp$ret$1;
          var tmp$ret$0;
          if (tmp0_safe_receiver.fastPrototype == null) {
            tmp0_safe_receiver.fastPrototype = getPrototype(ctor);
          }
          tmp$ret$0 = tmp0_safe_receiver.fastPrototype;
          tmp$ret$1 = tmp$ret$0;
          tmp = tmp$ret$1;
        }
        var tmp1_elvis_lhs = tmp;
        return tmp1_elvis_lhs == null ? getPrototype(ctor) : tmp1_elvis_lhs;
      }
      function extendCacheWithSingle(_this__u8e3s4, intr) {
        _this__u8e3s4.implementInterfaceMemo[getOrDefineInterfaceId(intr)] = true;
      }
      function extendCacheWith(_this__u8e3s4, cache) {
        var tmp0_safe_receiver = cache;
        var tmp1_elvis_lhs = tmp0_safe_receiver == null ? null : tmp0_safe_receiver.implementInterfaceMemo;
        var tmp;
        if (tmp1_elvis_lhs == null) {
          return Unit_getInstance();
        } else {
          tmp = tmp1_elvis_lhs;
        }
        var anotherInterfaceMemo = tmp;
        Object.assign(_this__u8e3s4.implementInterfaceMemo, anotherInterfaceMemo);
      }
      function getPrototype(_this__u8e3s4) {
        var tmp0_safe_receiver = _this__u8e3s4.prototype;
        var tmp;
        if (tmp0_safe_receiver == null) {
          tmp = null;
        } else {
          var tmp$ret$2;
          var tmp$ret$1;
          var tmp$ret$0;
          var tmp0_unsafeCast = Object.getPrototypeOf(tmp0_safe_receiver);
          tmp$ret$0 = tmp0_unsafeCast;
          tmp$ret$1 = tmp$ret$0;
          tmp$ret$2 = tmp$ret$1;
          tmp = tmp$ret$2;
        }
        return tmp;
      }
      function getOrDefineInterfaceId(_this__u8e3s4) {
        var tmp$ret$1;
        var tmp0_unsafeCast = _this__u8e3s4.$metadata$;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_unsafeCast;
        tmp$ret$1 = tmp$ret$0;
        var metadata = tmp$ret$1;
        var tmp0_elvis_lhs = metadata.interfaceId;
        var interfaceId = tmp0_elvis_lhs == null ? -1 : tmp0_elvis_lhs;
        var tmp;
        if (!equals(interfaceId, -1)) {
          tmp = interfaceId;
        } else {
          var tmp1 = interfacesCounter;
          interfacesCounter = tmp1 + 1 | 0;
          var result = tmp1;
          metadata.interfaceId = result;
          tmp = result;
        }
        return tmp;
      }
      function isArray(obj) {
        var tmp;
        if (isJsArray(obj)) {
          var tmp$ret$0;
          tmp$ret$0 = obj;
          tmp = !tmp$ret$0.$type$;
        } else {
          tmp = false;
        }
        return tmp;
      }
      function isObject3(obj) {
        var objTypeOf = typeof obj;
        var tmp0_subject = objTypeOf;
        switch (tmp0_subject) {
          case "string":
            return true;
          case "number":
            return true;
          case "boolean":
            return true;
          case "function":
            return true;
          default:
            return jsInstanceOf(obj, Object);
        }
      }
      function isSuspendFunction(obj, arity) {
        if (typeof obj === "function") {
          var tmp$ret$0;
          var tmp0_unsafeCast = obj.$arity;
          tmp$ret$0 = tmp0_unsafeCast;
          return tmp$ret$0 === arity;
        }
        if (typeof obj === "object" ? jsIn("$metadata$", obj.constructor) : false) {
          var tmp$ret$1;
          var tmp1_unsafeCast = obj.constructor;
          tmp$ret$1 = tmp1_unsafeCast;
          var tmp0_safe_receiver = tmp$ret$1.$metadata$;
          var tmp1_safe_receiver = tmp0_safe_receiver == null ? null : tmp0_safe_receiver.suspendArity;
          var tmp;
          if (tmp1_safe_receiver == null) {
            tmp = null;
          } else {
            var tmp$ret$2;
            var result = false;
            var tmp0_iterator = arrayIterator(tmp1_safe_receiver);
            $l$loop: while (tmp0_iterator.hasNext_bitz1p_k$()) {
              var item = tmp0_iterator.next_20eer_k$();
              if (arity === item) {
                result = true;
                break $l$loop;
              }
            }
            return result;
            tmp = tmp$ret$2;
          }
          var tmp2_elvis_lhs = tmp;
          return tmp2_elvis_lhs == null ? false : tmp2_elvis_lhs;
        }
        return false;
      }
      function isNumber2(a) {
        var tmp;
        if (typeof a === "number") {
          tmp = true;
        } else {
          tmp = a instanceof Long;
        }
        return tmp;
      }
      function isComparable(value) {
        var type = typeof value;
        return ((type === "string" ? true : type === "boolean") ? true : isNumber2(value)) ? true : isInterface(value, get_js(getKClass(Comparable)));
      }
      function isCharSequence(value) {
        return typeof value === "string" ? true : isInterface(value, get_js(getKClass(CharSequence)));
      }
      function isBooleanArray(a) {
        return isJsArray(a) ? a.$type$ === "BooleanArray" : false;
      }
      function isByteArray(a) {
        return jsInstanceOf(a, Int8Array);
      }
      function isShortArray(a) {
        return jsInstanceOf(a, Int16Array);
      }
      function isCharArray(a) {
        return jsInstanceOf(a, Uint16Array) ? a.$type$ === "CharArray" : false;
      }
      function isIntArray(a) {
        return jsInstanceOf(a, Int32Array);
      }
      function isFloatArray(a) {
        return jsInstanceOf(a, Float32Array);
      }
      function isLongArray(a) {
        return isJsArray(a) ? a.$type$ === "LongArray" : false;
      }
      function isDoubleArray(a) {
        return jsInstanceOf(a, Float64Array);
      }
      function interfaceMeta(name, interfaces, associatedObjectKey, associatedObjects, suspendArity) {
        return createMetadata("interface", name, interfaces, associatedObjectKey, associatedObjects, suspendArity, void 0);
      }
      function objectMeta(name, interfaces, associatedObjectKey, associatedObjects, suspendArity, fastPrototype) {
        return createMetadata("object", name, interfaces, associatedObjectKey, associatedObjects, suspendArity, fastPrototype);
      }
      function jsIsType(obj, jsClass) {
        if (jsClass === Object) {
          return isObject3(obj);
        }
        if ((obj == null ? true : jsClass == null) ? true : !(typeof obj === "object") ? !(typeof obj === "function") : false) {
          return false;
        }
        if (typeof jsClass === "function" ? jsInstanceOf(obj, jsClass) : false) {
          return true;
        }
        var proto = jsGetPrototypeOf(jsClass);
        var tmp0_safe_receiver = proto;
        var constructor = tmp0_safe_receiver == null ? null : tmp0_safe_receiver.constructor;
        if (constructor != null ? jsIn("$metadata$", constructor) : false) {
          var metadata = constructor.$metadata$;
          if (metadata.kind === "object") {
            return obj === jsClass;
          }
        }
        var klassMetadata = jsClass.$metadata$;
        if (klassMetadata == null) {
          return jsInstanceOf(obj, jsClass);
        }
        if (klassMetadata.kind === "interface" ? obj.constructor != null : false) {
          return isInterfaceImpl(obj.constructor, jsClass);
        }
        return false;
      }
      function jsGetPrototypeOf(jsClass) {
        return Object.getPrototypeOf(jsClass);
      }
      function throwLinkageError(message) {
        throw new IrLinkageError(message);
      }
      function IrLinkageError(message) {
        Error_init_$Init$_0(message, this);
        captureStack(this, IrLinkageError);
      }
      IrLinkageError.$metadata$ = classMeta("IrLinkageError", void 0, void 0, void 0, void 0, Error_0.prototype);
      function copyOf(_this__u8e3s4) {
        var tmp$ret$0;
        tmp$ret$0 = _this__u8e3s4;
        return tmp$ret$0.slice();
      }
      function copyOf_0(_this__u8e3s4) {
        var tmp$ret$0;
        tmp$ret$0 = _this__u8e3s4;
        return tmp$ret$0.slice();
      }
      function plus_1(_this__u8e3s4, elements) {
        var tmp$ret$0;
        tmp$ret$0 = _this__u8e3s4;
        return tmp$ret$0.concat(elements);
      }
      function copyOfRange(_this__u8e3s4, fromIndex, toIndex) {
        Companion_getInstance().checkRangeIndexes_5hjybp_k$(fromIndex, toIndex, _this__u8e3s4.length);
        var tmp$ret$0;
        tmp$ret$0 = _this__u8e3s4;
        return tmp$ret$0.slice(fromIndex, toIndex);
      }
      function copyInto(_this__u8e3s4, destination, destinationOffset, startIndex, endIndex) {
        arrayCopy(_this__u8e3s4, destination, destinationOffset, startIndex, endIndex);
        return destination;
      }
      function asList(_this__u8e3s4) {
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = _this__u8e3s4;
        tmp$ret$1 = tmp$ret$0;
        return new ArrayList(tmp$ret$1);
      }
      function contentEquals_3(_this__u8e3s4, other) {
        return contentEqualsInternal(_this__u8e3s4, other);
      }
      function contentEquals_4(_this__u8e3s4, other) {
        return contentEqualsInternal(_this__u8e3s4, other);
      }
      function contentEquals_5(_this__u8e3s4, other) {
        return contentEqualsInternal(_this__u8e3s4, other);
      }
      function contentEquals_6(_this__u8e3s4, other) {
        return contentEqualsInternal(_this__u8e3s4, other);
      }
      function contentEquals_7(_this__u8e3s4, other) {
        return contentEqualsInternal(_this__u8e3s4, other);
      }
      function contentEquals_8(_this__u8e3s4, other) {
        return contentEqualsInternal(_this__u8e3s4, other);
      }
      function contentEquals_9(_this__u8e3s4, other) {
        return contentEqualsInternal(_this__u8e3s4, other);
      }
      function contentEquals_10(_this__u8e3s4, other) {
        return contentEqualsInternal(_this__u8e3s4, other);
      }
      function contentEquals_11(_this__u8e3s4, other) {
        return contentEqualsInternal(_this__u8e3s4, other);
      }
      function minOf(a, b) {
        return Math.min(a, b);
      }
      function _get_resultContinuation__9wf8ix($this) {
        return $this.resultContinuation_1;
      }
      function _get__context__gmdhsr($this) {
        return $this._context_1;
      }
      function _set_intercepted___wojxxj($this, _set____db54di) {
        $this.intercepted__1 = _set____db54di;
      }
      function _get_intercepted___h4t7df($this) {
        return $this.intercepted__1;
      }
      function releaseIntercepted($this) {
        var intercepted = $this.intercepted__1;
        if (!(intercepted == null) ? !(intercepted === $this) : false) {
          ensureNotNull($this.get_context_h02k06_k$().get_1pi7hg_k$(Key_getInstance())).releaseInterceptedContinuation_4i98ok_k$(intercepted);
        }
        $this.intercepted__1 = CompletedContinuation_getInstance();
      }
      function CoroutineImpl(resultContinuation) {
        this.resultContinuation_1 = resultContinuation;
        this.state_1 = 0;
        this.exceptionState_1 = 0;
        this.result_1 = null;
        this.exception_1 = null;
        this.finallyPath_1 = null;
        var tmp = this;
        var tmp0_safe_receiver = this.resultContinuation_1;
        tmp._context_1 = tmp0_safe_receiver == null ? null : tmp0_safe_receiver.get_context_h02k06_k$();
        this.intercepted__1 = null;
      }
      CoroutineImpl.prototype.set_state_a96kl8_k$ = function(_set____db54di) {
        this.state_1 = _set____db54di;
      };
      CoroutineImpl.prototype.get_state_iypx7s_k$ = function() {
        return this.state_1;
      };
      CoroutineImpl.prototype.set_exceptionState_s9sevl_k$ = function(_set____db54di) {
        this.exceptionState_1 = _set____db54di;
      };
      CoroutineImpl.prototype.get_exceptionState_wflpxn_k$ = function() {
        return this.exceptionState_1;
      };
      CoroutineImpl.prototype.set_result_ximc09_k$ = function(_set____db54di) {
        this.result_1 = _set____db54di;
      };
      CoroutineImpl.prototype.get_result_iyg5d2_k$ = function() {
        return this.result_1;
      };
      CoroutineImpl.prototype.set_exception_pwgeox_k$ = function(_set____db54di) {
        this.exception_1 = _set____db54di;
      };
      CoroutineImpl.prototype.get_exception_x0n6w6_k$ = function() {
        return this.exception_1;
      };
      CoroutineImpl.prototype.set_finallyPath_gfcru6_k$ = function(_set____db54di) {
        this.finallyPath_1 = _set____db54di;
      };
      CoroutineImpl.prototype.get_finallyPath_aqs201_k$ = function() {
        return this.finallyPath_1;
      };
      CoroutineImpl.prototype.get_context_h02k06_k$ = function() {
        return ensureNotNull(this._context_1);
      };
      CoroutineImpl.prototype.intercepted_vh228x_k$ = function() {
        var tmp2_elvis_lhs = this.intercepted__1;
        var tmp;
        if (tmp2_elvis_lhs == null) {
          var tmp$ret$0;
          var tmp0_safe_receiver = this.get_context_h02k06_k$().get_1pi7hg_k$(Key_getInstance());
          var tmp1_elvis_lhs = tmp0_safe_receiver == null ? null : tmp0_safe_receiver.interceptContinuation_pbrjat_k$(this);
          var tmp0_also = tmp1_elvis_lhs == null ? this : tmp1_elvis_lhs;
          this.intercepted__1 = tmp0_also;
          tmp$ret$0 = tmp0_also;
          tmp = tmp$ret$0;
        } else {
          tmp = tmp2_elvis_lhs;
        }
        return tmp;
      };
      CoroutineImpl.prototype.resumeWith_7onugl_k$ = function(result) {
        var current = this;
        var tmp$ret$0;
        var tmp;
        if (_Result___get_isFailure__impl__jpiriv(result)) {
          tmp = null;
        } else {
          var tmp_0 = _Result___get_value__impl__bjfvqg(result);
          tmp = (tmp_0 == null ? true : isObject3(tmp_0)) ? tmp_0 : THROW_CCE();
        }
        tmp$ret$0 = tmp;
        var currentResult = tmp$ret$0;
        var currentException = Result__exceptionOrNull_impl_p6xea9(result);
        while (true) {
          var tmp$ret$6;
          var tmp0_with = current;
          if (currentException == null) {
            tmp0_with.result_1 = currentResult;
          } else {
            tmp0_with.state_1 = tmp0_with.exceptionState_1;
            tmp0_with.exception_1 = currentException;
          }
          try {
            var outcome = tmp0_with.doResume_5yljmg_k$();
            if (outcome === get_COROUTINE_SUSPENDED())
              return Unit_getInstance();
            currentResult = outcome;
            currentException = null;
          } catch ($p) {
            currentResult = null;
            var tmp$ret$1;
            tmp$ret$1 = $p;
            currentException = tmp$ret$1;
          }
          releaseIntercepted(tmp0_with);
          var completion = ensureNotNull(tmp0_with.resultContinuation_1);
          var tmp_1;
          if (completion instanceof CoroutineImpl) {
            current = completion;
            tmp_1 = Unit_getInstance();
          } else {
            if (!(currentException == null)) {
              var tmp$ret$3;
              var tmp0_resumeWithException = ensureNotNull(currentException);
              var tmp$ret$2;
              var tmp0_failure = Companion_getInstance_9();
              tmp$ret$2 = _Result___init__impl__xyqfz8(createFailure(tmp0_resumeWithException));
              completion.resumeWith_s3a3yh_k$(tmp$ret$2);
              tmp$ret$3 = Unit_getInstance();
            } else {
              var tmp$ret$5;
              var tmp1_resume = currentResult;
              var tmp$ret$4;
              var tmp0_success = Companion_getInstance_9();
              tmp$ret$4 = _Result___init__impl__xyqfz8(tmp1_resume);
              completion.resumeWith_s3a3yh_k$(tmp$ret$4);
              tmp$ret$5 = Unit_getInstance();
            }
            return Unit_getInstance();
          }
          tmp$ret$6 = tmp_1;
        }
      };
      CoroutineImpl.prototype.resumeWith_s3a3yh_k$ = function(result) {
        return this.resumeWith_7onugl_k$(result);
      };
      CoroutineImpl.prototype.create_lvr374_k$ = function(completion) {
        throw UnsupportedOperationException_init_$Create$_0("create(Continuation) has not been overridden");
      };
      CoroutineImpl.prototype.create_xubfvz_k$ = function(value, completion) {
        throw UnsupportedOperationException_init_$Create$_0("create(Any?;Continuation) has not been overridden");
      };
      CoroutineImpl.$metadata$ = classMeta("CoroutineImpl", [Continuation]);
      function CompletedContinuation() {
        CompletedContinuation_instance = this;
      }
      CompletedContinuation.prototype.get_context_h02k06_k$ = function() {
        throw IllegalStateException_init_$Create$_0("This continuation is already complete");
      };
      CompletedContinuation.prototype.resumeWith_7onugl_k$ = function(result) {
        throw IllegalStateException_init_$Create$_0("This continuation is already complete");
      };
      CompletedContinuation.prototype.resumeWith_s3a3yh_k$ = function(result) {
        return this.resumeWith_7onugl_k$(result);
      };
      CompletedContinuation.prototype.toString = function() {
        return "This continuation is already complete";
      };
      CompletedContinuation.$metadata$ = objectMeta("CompletedContinuation", [Continuation]);
      var CompletedContinuation_instance;
      function CompletedContinuation_getInstance() {
        if (CompletedContinuation_instance == null)
          new CompletedContinuation();
        return CompletedContinuation_instance;
      }
      function invokeSuspendSuperType(_this__u8e3s4, completion) {
        throw new NotImplementedError("It is intrinsic method");
      }
      function invokeSuspendSuperTypeWithReceiver(_this__u8e3s4, receiver, completion) {
        throw new NotImplementedError("It is intrinsic method");
      }
      function invokeSuspendSuperTypeWithReceiverAndParam(_this__u8e3s4, receiver, param, completion) {
        throw new NotImplementedError("It is intrinsic method");
      }
      function Exception_init_$Init$($this) {
        extendThrowable($this, void 0, void 0);
        Exception.call($this);
        return $this;
      }
      function Exception_init_$Create$() {
        var tmp = Exception_init_$Init$(Object.create(Exception.prototype));
        captureStack(tmp, Exception_init_$Create$);
        return tmp;
      }
      function Exception_init_$Init$_0(message, $this) {
        extendThrowable($this, message, void 0);
        Exception.call($this);
        return $this;
      }
      function Exception_init_$Create$_0(message) {
        var tmp = Exception_init_$Init$_0(message, Object.create(Exception.prototype));
        captureStack(tmp, Exception_init_$Create$_0);
        return tmp;
      }
      function Exception_init_$Init$_1(message, cause, $this) {
        extendThrowable($this, message, cause);
        Exception.call($this);
        return $this;
      }
      function Exception_init_$Create$_1(message, cause) {
        var tmp = Exception_init_$Init$_1(message, cause, Object.create(Exception.prototype));
        captureStack(tmp, Exception_init_$Create$_1);
        return tmp;
      }
      function Exception_init_$Init$_2(cause, $this) {
        extendThrowable($this, void 0, cause);
        Exception.call($this);
        return $this;
      }
      function Exception_init_$Create$_2(cause) {
        var tmp = Exception_init_$Init$_2(cause, Object.create(Exception.prototype));
        captureStack(tmp, Exception_init_$Create$_2);
        return tmp;
      }
      function Exception() {
        captureStack(this, Exception);
      }
      Exception.$metadata$ = classMeta("Exception", void 0, void 0, void 0, void 0, Error.prototype);
      function Error_init_$Init$($this) {
        extendThrowable($this, void 0, void 0);
        Error_0.call($this);
        return $this;
      }
      function Error_init_$Create$() {
        var tmp = Error_init_$Init$(Object.create(Error_0.prototype));
        captureStack(tmp, Error_init_$Create$);
        return tmp;
      }
      function Error_init_$Init$_0(message, $this) {
        extendThrowable($this, message, void 0);
        Error_0.call($this);
        return $this;
      }
      function Error_init_$Create$_0(message) {
        var tmp = Error_init_$Init$_0(message, Object.create(Error_0.prototype));
        captureStack(tmp, Error_init_$Create$_0);
        return tmp;
      }
      function Error_init_$Init$_1(message, cause, $this) {
        extendThrowable($this, message, cause);
        Error_0.call($this);
        return $this;
      }
      function Error_init_$Create$_1(message, cause) {
        var tmp = Error_init_$Init$_1(message, cause, Object.create(Error_0.prototype));
        captureStack(tmp, Error_init_$Create$_1);
        return tmp;
      }
      function Error_init_$Init$_2(cause, $this) {
        extendThrowable($this, void 0, cause);
        Error_0.call($this);
        return $this;
      }
      function Error_init_$Create$_2(cause) {
        var tmp = Error_init_$Init$_2(cause, Object.create(Error_0.prototype));
        captureStack(tmp, Error_init_$Create$_2);
        return tmp;
      }
      function Error_0() {
        captureStack(this, Error_0);
      }
      Error_0.$metadata$ = classMeta("Error", void 0, void 0, void 0, void 0, Error.prototype);
      function IllegalArgumentException_init_$Init$($this) {
        RuntimeException_init_$Init$($this);
        IllegalArgumentException.call($this);
        return $this;
      }
      function IllegalArgumentException_init_$Create$() {
        var tmp = IllegalArgumentException_init_$Init$(Object.create(IllegalArgumentException.prototype));
        captureStack(tmp, IllegalArgumentException_init_$Create$);
        return tmp;
      }
      function IllegalArgumentException_init_$Init$_0(message, $this) {
        RuntimeException_init_$Init$_0(message, $this);
        IllegalArgumentException.call($this);
        return $this;
      }
      function IllegalArgumentException_init_$Create$_0(message) {
        var tmp = IllegalArgumentException_init_$Init$_0(message, Object.create(IllegalArgumentException.prototype));
        captureStack(tmp, IllegalArgumentException_init_$Create$_0);
        return tmp;
      }
      function IllegalArgumentException_init_$Init$_1(message, cause, $this) {
        RuntimeException_init_$Init$_1(message, cause, $this);
        IllegalArgumentException.call($this);
        return $this;
      }
      function IllegalArgumentException_init_$Create$_1(message, cause) {
        var tmp = IllegalArgumentException_init_$Init$_1(message, cause, Object.create(IllegalArgumentException.prototype));
        captureStack(tmp, IllegalArgumentException_init_$Create$_1);
        return tmp;
      }
      function IllegalArgumentException_init_$Init$_2(cause, $this) {
        RuntimeException_init_$Init$_2(cause, $this);
        IllegalArgumentException.call($this);
        return $this;
      }
      function IllegalArgumentException_init_$Create$_2(cause) {
        var tmp = IllegalArgumentException_init_$Init$_2(cause, Object.create(IllegalArgumentException.prototype));
        captureStack(tmp, IllegalArgumentException_init_$Create$_2);
        return tmp;
      }
      function IllegalArgumentException() {
        captureStack(this, IllegalArgumentException);
      }
      IllegalArgumentException.$metadata$ = classMeta("IllegalArgumentException", void 0, void 0, void 0, void 0, RuntimeException.prototype);
      function IllegalStateException_init_$Init$($this) {
        RuntimeException_init_$Init$($this);
        IllegalStateException.call($this);
        return $this;
      }
      function IllegalStateException_init_$Create$() {
        var tmp = IllegalStateException_init_$Init$(Object.create(IllegalStateException.prototype));
        captureStack(tmp, IllegalStateException_init_$Create$);
        return tmp;
      }
      function IllegalStateException_init_$Init$_0(message, $this) {
        RuntimeException_init_$Init$_0(message, $this);
        IllegalStateException.call($this);
        return $this;
      }
      function IllegalStateException_init_$Create$_0(message) {
        var tmp = IllegalStateException_init_$Init$_0(message, Object.create(IllegalStateException.prototype));
        captureStack(tmp, IllegalStateException_init_$Create$_0);
        return tmp;
      }
      function IllegalStateException_init_$Init$_1(message, cause, $this) {
        RuntimeException_init_$Init$_1(message, cause, $this);
        IllegalStateException.call($this);
        return $this;
      }
      function IllegalStateException_init_$Create$_1(message, cause) {
        var tmp = IllegalStateException_init_$Init$_1(message, cause, Object.create(IllegalStateException.prototype));
        captureStack(tmp, IllegalStateException_init_$Create$_1);
        return tmp;
      }
      function IllegalStateException_init_$Init$_2(cause, $this) {
        RuntimeException_init_$Init$_2(cause, $this);
        IllegalStateException.call($this);
        return $this;
      }
      function IllegalStateException_init_$Create$_2(cause) {
        var tmp = IllegalStateException_init_$Init$_2(cause, Object.create(IllegalStateException.prototype));
        captureStack(tmp, IllegalStateException_init_$Create$_2);
        return tmp;
      }
      function IllegalStateException() {
        captureStack(this, IllegalStateException);
      }
      IllegalStateException.$metadata$ = classMeta("IllegalStateException", void 0, void 0, void 0, void 0, RuntimeException.prototype);
      function NoSuchElementException_init_$Init$($this) {
        RuntimeException_init_$Init$($this);
        NoSuchElementException.call($this);
        return $this;
      }
      function NoSuchElementException_init_$Create$() {
        var tmp = NoSuchElementException_init_$Init$(Object.create(NoSuchElementException.prototype));
        captureStack(tmp, NoSuchElementException_init_$Create$);
        return tmp;
      }
      function NoSuchElementException_init_$Init$_0(message, $this) {
        RuntimeException_init_$Init$_0(message, $this);
        NoSuchElementException.call($this);
        return $this;
      }
      function NoSuchElementException_init_$Create$_0(message) {
        var tmp = NoSuchElementException_init_$Init$_0(message, Object.create(NoSuchElementException.prototype));
        captureStack(tmp, NoSuchElementException_init_$Create$_0);
        return tmp;
      }
      function NoSuchElementException() {
        captureStack(this, NoSuchElementException);
      }
      NoSuchElementException.$metadata$ = classMeta("NoSuchElementException", void 0, void 0, void 0, void 0, RuntimeException.prototype);
      function RuntimeException_init_$Init$($this) {
        Exception_init_$Init$($this);
        RuntimeException.call($this);
        return $this;
      }
      function RuntimeException_init_$Create$() {
        var tmp = RuntimeException_init_$Init$(Object.create(RuntimeException.prototype));
        captureStack(tmp, RuntimeException_init_$Create$);
        return tmp;
      }
      function RuntimeException_init_$Init$_0(message, $this) {
        Exception_init_$Init$_0(message, $this);
        RuntimeException.call($this);
        return $this;
      }
      function RuntimeException_init_$Create$_0(message) {
        var tmp = RuntimeException_init_$Init$_0(message, Object.create(RuntimeException.prototype));
        captureStack(tmp, RuntimeException_init_$Create$_0);
        return tmp;
      }
      function RuntimeException_init_$Init$_1(message, cause, $this) {
        Exception_init_$Init$_1(message, cause, $this);
        RuntimeException.call($this);
        return $this;
      }
      function RuntimeException_init_$Create$_1(message, cause) {
        var tmp = RuntimeException_init_$Init$_1(message, cause, Object.create(RuntimeException.prototype));
        captureStack(tmp, RuntimeException_init_$Create$_1);
        return tmp;
      }
      function RuntimeException_init_$Init$_2(cause, $this) {
        Exception_init_$Init$_2(cause, $this);
        RuntimeException.call($this);
        return $this;
      }
      function RuntimeException_init_$Create$_2(cause) {
        var tmp = RuntimeException_init_$Init$_2(cause, Object.create(RuntimeException.prototype));
        captureStack(tmp, RuntimeException_init_$Create$_2);
        return tmp;
      }
      function RuntimeException() {
        captureStack(this, RuntimeException);
      }
      RuntimeException.$metadata$ = classMeta("RuntimeException", void 0, void 0, void 0, void 0, Exception.prototype);
      function UnsupportedOperationException_init_$Init$($this) {
        RuntimeException_init_$Init$($this);
        UnsupportedOperationException.call($this);
        return $this;
      }
      function UnsupportedOperationException_init_$Create$() {
        var tmp = UnsupportedOperationException_init_$Init$(Object.create(UnsupportedOperationException.prototype));
        captureStack(tmp, UnsupportedOperationException_init_$Create$);
        return tmp;
      }
      function UnsupportedOperationException_init_$Init$_0(message, $this) {
        RuntimeException_init_$Init$_0(message, $this);
        UnsupportedOperationException.call($this);
        return $this;
      }
      function UnsupportedOperationException_init_$Create$_0(message) {
        var tmp = UnsupportedOperationException_init_$Init$_0(message, Object.create(UnsupportedOperationException.prototype));
        captureStack(tmp, UnsupportedOperationException_init_$Create$_0);
        return tmp;
      }
      function UnsupportedOperationException_init_$Init$_1(message, cause, $this) {
        RuntimeException_init_$Init$_1(message, cause, $this);
        UnsupportedOperationException.call($this);
        return $this;
      }
      function UnsupportedOperationException_init_$Create$_1(message, cause) {
        var tmp = UnsupportedOperationException_init_$Init$_1(message, cause, Object.create(UnsupportedOperationException.prototype));
        captureStack(tmp, UnsupportedOperationException_init_$Create$_1);
        return tmp;
      }
      function UnsupportedOperationException_init_$Init$_2(cause, $this) {
        RuntimeException_init_$Init$_2(cause, $this);
        UnsupportedOperationException.call($this);
        return $this;
      }
      function UnsupportedOperationException_init_$Create$_2(cause) {
        var tmp = UnsupportedOperationException_init_$Init$_2(cause, Object.create(UnsupportedOperationException.prototype));
        captureStack(tmp, UnsupportedOperationException_init_$Create$_2);
        return tmp;
      }
      function UnsupportedOperationException() {
        captureStack(this, UnsupportedOperationException);
      }
      UnsupportedOperationException.$metadata$ = classMeta("UnsupportedOperationException", void 0, void 0, void 0, void 0, RuntimeException.prototype);
      function IndexOutOfBoundsException_init_$Init$($this) {
        RuntimeException_init_$Init$($this);
        IndexOutOfBoundsException.call($this);
        return $this;
      }
      function IndexOutOfBoundsException_init_$Create$() {
        var tmp = IndexOutOfBoundsException_init_$Init$(Object.create(IndexOutOfBoundsException.prototype));
        captureStack(tmp, IndexOutOfBoundsException_init_$Create$);
        return tmp;
      }
      function IndexOutOfBoundsException_init_$Init$_0(message, $this) {
        RuntimeException_init_$Init$_0(message, $this);
        IndexOutOfBoundsException.call($this);
        return $this;
      }
      function IndexOutOfBoundsException_init_$Create$_0(message) {
        var tmp = IndexOutOfBoundsException_init_$Init$_0(message, Object.create(IndexOutOfBoundsException.prototype));
        captureStack(tmp, IndexOutOfBoundsException_init_$Create$_0);
        return tmp;
      }
      function IndexOutOfBoundsException() {
        captureStack(this, IndexOutOfBoundsException);
      }
      IndexOutOfBoundsException.$metadata$ = classMeta("IndexOutOfBoundsException", void 0, void 0, void 0, void 0, RuntimeException.prototype);
      function NullPointerException_init_$Init$($this) {
        RuntimeException_init_$Init$($this);
        NullPointerException.call($this);
        return $this;
      }
      function NullPointerException_init_$Create$() {
        var tmp = NullPointerException_init_$Init$(Object.create(NullPointerException.prototype));
        captureStack(tmp, NullPointerException_init_$Create$);
        return tmp;
      }
      function NullPointerException_init_$Init$_0(message, $this) {
        RuntimeException_init_$Init$_0(message, $this);
        NullPointerException.call($this);
        return $this;
      }
      function NullPointerException_init_$Create$_0(message) {
        var tmp = NullPointerException_init_$Init$_0(message, Object.create(NullPointerException.prototype));
        captureStack(tmp, NullPointerException_init_$Create$_0);
        return tmp;
      }
      function NullPointerException() {
        captureStack(this, NullPointerException);
      }
      NullPointerException.$metadata$ = classMeta("NullPointerException", void 0, void 0, void 0, void 0, RuntimeException.prototype);
      function NoWhenBranchMatchedException_init_$Init$($this) {
        RuntimeException_init_$Init$($this);
        NoWhenBranchMatchedException.call($this);
        return $this;
      }
      function NoWhenBranchMatchedException_init_$Create$() {
        var tmp = NoWhenBranchMatchedException_init_$Init$(Object.create(NoWhenBranchMatchedException.prototype));
        captureStack(tmp, NoWhenBranchMatchedException_init_$Create$);
        return tmp;
      }
      function NoWhenBranchMatchedException_init_$Init$_0(message, $this) {
        RuntimeException_init_$Init$_0(message, $this);
        NoWhenBranchMatchedException.call($this);
        return $this;
      }
      function NoWhenBranchMatchedException_init_$Create$_0(message) {
        var tmp = NoWhenBranchMatchedException_init_$Init$_0(message, Object.create(NoWhenBranchMatchedException.prototype));
        captureStack(tmp, NoWhenBranchMatchedException_init_$Create$_0);
        return tmp;
      }
      function NoWhenBranchMatchedException_init_$Init$_1(message, cause, $this) {
        RuntimeException_init_$Init$_1(message, cause, $this);
        NoWhenBranchMatchedException.call($this);
        return $this;
      }
      function NoWhenBranchMatchedException_init_$Create$_1(message, cause) {
        var tmp = NoWhenBranchMatchedException_init_$Init$_1(message, cause, Object.create(NoWhenBranchMatchedException.prototype));
        captureStack(tmp, NoWhenBranchMatchedException_init_$Create$_1);
        return tmp;
      }
      function NoWhenBranchMatchedException_init_$Init$_2(cause, $this) {
        RuntimeException_init_$Init$_2(cause, $this);
        NoWhenBranchMatchedException.call($this);
        return $this;
      }
      function NoWhenBranchMatchedException_init_$Create$_2(cause) {
        var tmp = NoWhenBranchMatchedException_init_$Init$_2(cause, Object.create(NoWhenBranchMatchedException.prototype));
        captureStack(tmp, NoWhenBranchMatchedException_init_$Create$_2);
        return tmp;
      }
      function NoWhenBranchMatchedException() {
        captureStack(this, NoWhenBranchMatchedException);
      }
      NoWhenBranchMatchedException.$metadata$ = classMeta("NoWhenBranchMatchedException", void 0, void 0, void 0, void 0, RuntimeException.prototype);
      function ClassCastException_init_$Init$($this) {
        RuntimeException_init_$Init$($this);
        ClassCastException.call($this);
        return $this;
      }
      function ClassCastException_init_$Create$() {
        var tmp = ClassCastException_init_$Init$(Object.create(ClassCastException.prototype));
        captureStack(tmp, ClassCastException_init_$Create$);
        return tmp;
      }
      function ClassCastException_init_$Init$_0(message, $this) {
        RuntimeException_init_$Init$_0(message, $this);
        ClassCastException.call($this);
        return $this;
      }
      function ClassCastException_init_$Create$_0(message) {
        var tmp = ClassCastException_init_$Init$_0(message, Object.create(ClassCastException.prototype));
        captureStack(tmp, ClassCastException_init_$Create$_0);
        return tmp;
      }
      function ClassCastException() {
        captureStack(this, ClassCastException);
      }
      ClassCastException.$metadata$ = classMeta("ClassCastException", void 0, void 0, void 0, void 0, RuntimeException.prototype);
      function UninitializedPropertyAccessException_init_$Init$($this) {
        RuntimeException_init_$Init$($this);
        UninitializedPropertyAccessException.call($this);
        return $this;
      }
      function UninitializedPropertyAccessException_init_$Create$() {
        var tmp = UninitializedPropertyAccessException_init_$Init$(Object.create(UninitializedPropertyAccessException.prototype));
        captureStack(tmp, UninitializedPropertyAccessException_init_$Create$);
        return tmp;
      }
      function UninitializedPropertyAccessException_init_$Init$_0(message, $this) {
        RuntimeException_init_$Init$_0(message, $this);
        UninitializedPropertyAccessException.call($this);
        return $this;
      }
      function UninitializedPropertyAccessException_init_$Create$_0(message) {
        var tmp = UninitializedPropertyAccessException_init_$Init$_0(message, Object.create(UninitializedPropertyAccessException.prototype));
        captureStack(tmp, UninitializedPropertyAccessException_init_$Create$_0);
        return tmp;
      }
      function UninitializedPropertyAccessException_init_$Init$_1(message, cause, $this) {
        RuntimeException_init_$Init$_1(message, cause, $this);
        UninitializedPropertyAccessException.call($this);
        return $this;
      }
      function UninitializedPropertyAccessException_init_$Create$_1(message, cause) {
        var tmp = UninitializedPropertyAccessException_init_$Init$_1(message, cause, Object.create(UninitializedPropertyAccessException.prototype));
        captureStack(tmp, UninitializedPropertyAccessException_init_$Create$_1);
        return tmp;
      }
      function UninitializedPropertyAccessException_init_$Init$_2(cause, $this) {
        RuntimeException_init_$Init$_2(cause, $this);
        UninitializedPropertyAccessException.call($this);
        return $this;
      }
      function UninitializedPropertyAccessException_init_$Create$_2(cause) {
        var tmp = UninitializedPropertyAccessException_init_$Init$_2(cause, Object.create(UninitializedPropertyAccessException.prototype));
        captureStack(tmp, UninitializedPropertyAccessException_init_$Create$_2);
        return tmp;
      }
      function UninitializedPropertyAccessException() {
        captureStack(this, UninitializedPropertyAccessException);
      }
      UninitializedPropertyAccessException.$metadata$ = classMeta("UninitializedPropertyAccessException", void 0, void 0, void 0, void 0, RuntimeException.prototype);
      function jsIn(lhs_hack, rhs_hack) {
        var tmp$ret$0;
        var tmp0_unsafeCast = lhs_hack in rhs_hack;
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function jsBitwiseOr(lhs_hack, rhs_hack) {
        var tmp$ret$0;
        var tmp0_unsafeCast = lhs_hack | rhs_hack;
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function jsTypeOf(value_hack) {
        var tmp$ret$0;
        var tmp0_unsafeCast = typeof value_hack;
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function jsInstanceOf(obj_hack, jsClass_hack) {
        var tmp$ret$0;
        var tmp0_unsafeCast = obj_hack instanceof jsClass_hack;
        tmp$ret$0 = tmp0_unsafeCast;
        return tmp$ret$0;
      }
      function fromBits(_this__u8e3s4, bits) {
        return doubleFromBits(bits);
      }
      function toRawBits(_this__u8e3s4) {
        return doubleToRawBits(_this__u8e3s4);
      }
      function toString_2(_this__u8e3s4, radix) {
        return toStringImpl(_this__u8e3s4, checkRadix(radix));
      }
      function Function1() {
      }
      Function1.$metadata$ = interfaceMeta("Function1");
      function Function0() {
      }
      Function0.$metadata$ = interfaceMeta("Function0");
      function Function2() {
      }
      Function2.$metadata$ = interfaceMeta("Function2");
      function Function3() {
      }
      Function3.$metadata$ = interfaceMeta("Function3");
      function KFunction2() {
      }
      KFunction2.$metadata$ = interfaceMeta("KFunction2");
      function KFunction1() {
      }
      KFunction1.$metadata$ = interfaceMeta("KFunction1");
      function SuspendFunction0() {
      }
      SuspendFunction0.$metadata$ = interfaceMeta("SuspendFunction0");
      function SuspendFunction1() {
      }
      SuspendFunction1.$metadata$ = interfaceMeta("SuspendFunction1");
      function SuspendFunction2() {
      }
      SuspendFunction2.$metadata$ = interfaceMeta("SuspendFunction2");
      CombinedContext.prototype.plus_rgw9wi_k$ = plus;
      PI = 3.141592653589793;
      _stableSortingIsSupported = null;
      OBJECT_HASH_CODE_PROPERTY_NAME = "kotlinHashCodeValue$";
      POW_2_32 = 4294967296;
      TWO_PWR_32_DBL_ = 4294967296;
      TWO_PWR_63_DBL_ = 9223372036854776e3;
      interfacesCounter = 0;
      _.$_$ = _.$_$ || {};
      _.$_$.a = ArrayList_init_$Create$;
      _.$_$.b = IllegalArgumentException_init_$Create$_0;
      _.$_$.c = IllegalStateException_init_$Create$_0;
      _.$_$.d = RuntimeException_init_$Create$_0;
      _.$_$.e = _Char___init__impl__6a9atx;
      _.$_$.f = Default_getInstance;
      _.$_$.g = Unit_getInstance;
      _.$_$.h = println;
      _.$_$.i = classMeta;
      _.$_$.j = fillArrayVal;
      _.$_$.k = numberToInt;
      _.$_$.l = objectMeta;
      _.$_$.m = toLong;
      _.$_$.n = toString_1;
      _.$_$.o = get_PI;
      _.$_$.p = roundToInt_0;
      _.$_$.q = round;
      _.$_$.r = Char_0;
      _.$_$.s = Enum;
      _.$_$.t = THROW_ISE;
      _.$_$.u = ensureNotNull;
      _.$_$.v = throwUninitializedPropertyAccessException;
      return _;
    });
  }
});

// node_modules/oregondsp/kotlin/oregondsp.js
var require_oregondsp = __commonJS({
  "node_modules/oregondsp/kotlin/oregondsp.js"(exports, module) {
    (function(root2, factory) {
      if (typeof define === "function" && define.amd)
        define(["exports", "./kotlin-kotlin-stdlib-js-ir.js"], factory);
      else if (typeof exports === "object")
        factory(module.exports, require_kotlin_kotlin_stdlib_js_ir());
      else {
        if (typeof this["kotlin-kotlin-stdlib-js-ir"] === "undefined") {
          throw new Error("Error loading module 'oregondsp'. Its dependency 'kotlin-kotlin-stdlib-js-ir' was not found. Please, check whether 'kotlin-kotlin-stdlib-js-ir' is loaded prior to 'oregondsp'.");
        }
        root2.oregondsp = factory(typeof oregondsp === "undefined" ? {} : oregondsp, this["kotlin-kotlin-stdlib-js-ir"]);
      }
    })(exports, function(_, kotlin_kotlin) {
      "use strict";
      var imul = Math.imul;
      var get_PI = kotlin_kotlin.$_$.o;
      var Unit_getInstance = kotlin_kotlin.$_$.g;
      var classMeta = kotlin_kotlin.$_$.i;
      var objectMeta = kotlin_kotlin.$_$.l;
      var IllegalArgumentException_init_$Create$ = kotlin_kotlin.$_$.b;
      var throwUninitializedPropertyAccessException = kotlin_kotlin.$_$.v;
      var IllegalStateException_init_$Create$ = kotlin_kotlin.$_$.c;
      var ensureNotNull = kotlin_kotlin.$_$.u;
      var _Char___init__impl__6a9atx = kotlin_kotlin.$_$.e;
      var Char = kotlin_kotlin.$_$.r;
      var toLong = kotlin_kotlin.$_$.m;
      var toString = kotlin_kotlin.$_$.n;
      var ArrayList_init_$Create$ = kotlin_kotlin.$_$.a;
      var fillArrayVal = kotlin_kotlin.$_$.j;
      var RuntimeException_init_$Create$ = kotlin_kotlin.$_$.d;
      var round = kotlin_kotlin.$_$.q;
      var numberToInt = kotlin_kotlin.$_$.k;
      var Default_getInstance = kotlin_kotlin.$_$.f;
      var roundToInt = kotlin_kotlin.$_$.p;
      var println = kotlin_kotlin.$_$.h;
      var THROW_ISE = kotlin_kotlin.$_$.t;
      var Enum = kotlin_kotlin.$_$.s;
      HammingWindow2.prototype = Object.create(Window2.prototype);
      HammingWindow2.prototype.constructor = HammingWindow2;
      HanningWindow2.prototype = Object.create(Window2.prototype);
      HanningWindow2.prototype.constructor = HanningWindow2;
      CDFTsr16.prototype = Object.create(CDFTsr.prototype);
      CDFTsr16.prototype.constructor = CDFTsr16;
      CDFTsr8.prototype = Object.create(CDFTsr.prototype);
      CDFTsr8.prototype.constructor = CDFTsr8;
      FIRTypeIII2.prototype = Object.create(EquirippleFIRFilter2.prototype);
      FIRTypeIII2.prototype.constructor = FIRTypeIII2;
      CenteredDifferentiator2.prototype = Object.create(FIRTypeIII2.prototype);
      CenteredDifferentiator2.prototype.constructor = CenteredDifferentiator2;
      CenteredHilbertTransform2.prototype = Object.create(FIRTypeIII2.prototype);
      CenteredHilbertTransform2.prototype.constructor = CenteredHilbertTransform2;
      FIRTypeI2.prototype = Object.create(EquirippleFIRFilter2.prototype);
      FIRTypeI2.prototype.constructor = FIRTypeI2;
      EquirippleBandpass2.prototype = Object.create(FIRTypeI2.prototype);
      EquirippleBandpass2.prototype.constructor = EquirippleBandpass2;
      FIRTypeII2.prototype = Object.create(EquirippleFIRFilter2.prototype);
      FIRTypeII2.prototype.constructor = FIRTypeII2;
      EquirippleHalfBandPrototype.prototype = Object.create(FIRTypeII2.prototype);
      EquirippleHalfBandPrototype.prototype.constructor = EquirippleHalfBandPrototype;
      EquirippleHighpass2.prototype = Object.create(FIRTypeI2.prototype);
      EquirippleHighpass2.prototype.constructor = EquirippleHighpass2;
      EquirippleLowpass2.prototype = Object.create(FIRTypeI2.prototype);
      EquirippleLowpass2.prototype.constructor = EquirippleLowpass2;
      FIRTypeIV.prototype = Object.create(EquirippleFIRFilter2.prototype);
      FIRTypeIV.prototype.constructor = FIRTypeIV;
      StaggeredDifferentiator2.prototype = Object.create(FIRTypeIV.prototype);
      StaggeredDifferentiator2.prototype.constructor = StaggeredDifferentiator2;
      StaggeredHilbertTranform2.prototype = Object.create(FIRTypeIV.prototype);
      StaggeredHilbertTranform2.prototype.constructor = StaggeredHilbertTranform2;
      AnalogButterworth.prototype = Object.create(AnalogPrototype2.prototype);
      AnalogButterworth.prototype.constructor = AnalogButterworth;
      AnalogChebyshevI.prototype = Object.create(AnalogPrototype2.prototype);
      AnalogChebyshevI.prototype.constructor = AnalogChebyshevI;
      AnalogChebyshevII.prototype = Object.create(AnalogPrototype2.prototype);
      AnalogChebyshevII.prototype.constructor = AnalogChebyshevII;
      Butterworth2.prototype = Object.create(IIRFilter3.prototype);
      Butterworth2.prototype.constructor = Butterworth2;
      ChebyshevI2.prototype = Object.create(IIRFilter3.prototype);
      ChebyshevI2.prototype.constructor = ChebyshevI2;
      ChebyshevII2.prototype = Object.create(IIRFilter3.prototype);
      ChebyshevII2.prototype.constructor = ChebyshevII2;
      PassbandType2.prototype = Object.create(Enum.prototype);
      PassbandType2.prototype.constructor = PassbandType2;
      ThiranAllpass2.prototype = Object.create(Allpass2.prototype);
      ThiranAllpass2.prototype.constructor = ThiranAllpass2;
      function HammingWindow2(N) {
        Window2.call(this, N);
        var inductionVariable = 0;
        var last = N - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp = this.w_1;
            var tmp$ret$0;
            var tmp0_cos = -get_PI() + i * 2 * get_PI() / (N - 1 | 0);
            tmp$ret$0 = Math.cos(tmp0_cos);
            tmp[i] = 0.54 + 0.46 * tmp$ret$0;
          } while (!(i === last));
      }
      HammingWindow2.$metadata$ = classMeta("HammingWindow", void 0, void 0, void 0, void 0, Window2.prototype);
      function HanningWindow2(N) {
        Window2.call(this, N);
        var inductionVariable = 0;
        var last = N - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp = this.w_1;
            var tmp$ret$0;
            var tmp0_cos = -get_PI() + i * 2 * get_PI() / (N - 1 | 0);
            tmp$ret$0 = Math.cos(tmp0_cos);
            tmp[i] = 0.5 + 0.5 * tmp$ret$0;
          } while (!(i === last));
      }
      HanningWindow2.$metadata$ = classMeta("HanningWindow", void 0, void 0, void 0, void 0, Window2.prototype);
      function Sequence_init_$Init$(x2, $this) {
        Sequence2.call($this);
        $this.array_1 = new Float32Array(x2.length);
        var tmp = $this;
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = x2;
        tmp$ret$1 = tmp$ret$0.slice();
        tmp.array_1 = tmp$ret$1;
        return $this;
      }
      function Sequence_fromArray(x2) {
        return Sequence_init_$Init$(x2, Object.create(Sequence2.prototype));
      }
      function Sequence_init_$Init$_0(N, $this) {
        Sequence2.call($this);
        $this.array_1 = new Float32Array(N);
        return $this;
      }
      function Sequence_ofSize(N) {
        return Sequence_init_$Init$_0(N, Object.create(Sequence2.prototype));
      }
      function Companion() {
        Companion_instance = this;
      }
      Companion.prototype.aliasArray = function(src, dst) {
        var slength = src.length;
        var dlength = dst.length;
        var inductionVariable = 0;
        if (inductionVariable <= dlength)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            dst[i] = 0;
          } while (!(i === dlength));
        var inductionVariable_0 = 0;
        var last = slength - 1 | 0;
        if (inductionVariable_0 <= last)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var tmp2_array = dst;
            var tmp3_index0 = i_0 % dlength | 0;
            tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] + src[i_0];
          } while (!(i_0 === last));
      };
      Companion.prototype.reverseArray = function(y2) {
        var i = 0;
        var j = y2.length - 1 | 0;
        while (i < j) {
          var tmp = y2[i];
          y2[i] = y2[j];
          y2[j] = tmp;
          var tmp0 = i;
          i = tmp0 + 1 | 0;
          var tmp1 = j;
          j = tmp1 - 1 | 0;
        }
      };
      Companion.prototype.rmeanArray = function(y2) {
        var mean = 0;
        var inductionVariable = 0;
        var last = y2.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            mean = mean + y2[i];
          } while (inductionVariable <= last);
        mean = mean / y2.length;
        var inductionVariable_0 = 0;
        var last_0 = y2.length - 1 | 0;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var tmp2_array = y2;
            var tmp3_index0 = i_0;
            tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] - mean;
          } while (inductionVariable_0 <= last_0);
      };
      Companion.prototype.circularShiftArray = function(y2, shift) {
        var N = y2.length;
        var s2 = shift % N | 0;
        if (s2 > 0 ? (N - s2 | 0) < s2 : false)
          s2 = s2 - N | 0;
        else if (s2 < 0 ? (N + s2 | 0) < (-s2 | 0) : false)
          s2 = s2 + N | 0;
        if (s2 < 0)
          s2 = imul(s2, -1);
        var tmp = new Float32Array(s2);
        if (s2 > 0) {
          var inductionVariable = 0;
          var last = s2 - 1 | 0;
          if (inductionVariable <= last)
            do {
              var i = inductionVariable;
              inductionVariable = inductionVariable + 1 | 0;
              tmp[i] = y2[(N - s2 | 0) + i | 0];
            } while (!(i === last));
          var inductionVariable_0 = (N - 1 | 0) - s2 | 0;
          if (0 <= inductionVariable_0)
            do {
              var i_0 = inductionVariable_0;
              inductionVariable_0 = inductionVariable_0 + -1 | 0;
              y2[i_0 + s2 | 0] = y2[i_0];
            } while (0 <= inductionVariable_0);
          var inductionVariable_1 = 0;
          var last_0 = s2 - 1 | 0;
          if (inductionVariable_1 <= last_0)
            do {
              var i_1 = inductionVariable_1;
              inductionVariable_1 = inductionVariable_1 + 1 | 0;
              y2[i_1] = tmp[i_1];
            } while (!(i_1 === last_0));
        }
        if (s2 < 0) {
          var inductionVariable_2 = 0;
          var last_1 = (-s2 | 0) - 1 | 0;
          if (inductionVariable_2 <= last_1)
            do {
              var i_2 = inductionVariable_2;
              inductionVariable_2 = inductionVariable_2 + 1 | 0;
              tmp[i_2] = y2[i_2];
            } while (!(i_2 === last_1));
          var inductionVariable_3 = -s2 | 0;
          var last_2 = N - 1 | 0;
          if (inductionVariable_3 <= last_2)
            do {
              var i_3 = inductionVariable_3;
              inductionVariable_3 = inductionVariable_3 + 1 | 0;
              y2[i_3 + s2 | 0] = y2[i_3];
            } while (!(i_3 === last_2));
          var inductionVariable_4 = 0;
          var last_3 = (-s2 | 0) - 1 | 0;
          if (inductionVariable_4 <= last_3)
            do {
              var i_4 = inductionVariable_4;
              inductionVariable_4 = inductionVariable_4 + 1 | 0;
              y2[(N + s2 | 0) + i_4 | 0] = tmp[i_4];
            } while (!(i_4 === last_3));
        }
      };
      Companion.prototype.zeroShiftArray = function(y2, shift) {
        if (imul(-1, shift) >= y2.length ? true : shift >= y2.length) {
          var inductionVariable = 0;
          var last = y2.length;
          if (inductionVariable <= last)
            do {
              var i = inductionVariable;
              inductionVariable = inductionVariable + 1 | 0;
              y2[i] = 0;
            } while (!(i === last));
        } else if (shift > 0) {
          var inductionVariable_0 = y2.length - 1 | 0;
          if (shift <= inductionVariable_0)
            do {
              var i_0 = inductionVariable_0;
              inductionVariable_0 = inductionVariable_0 + -1 | 0;
              y2[i_0] = y2[i_0 - shift | 0];
            } while (!(i_0 === shift));
          var inductionVariable_1 = 0;
          var last_0 = shift - 1 | 0;
          if (inductionVariable_1 <= last_0)
            do {
              var i_1 = inductionVariable_1;
              inductionVariable_1 = inductionVariable_1 + 1 | 0;
              y2[i_1] = 0;
            } while (!(i_1 === last_0));
        } else if (shift < 0) {
          var inductionVariable_2 = 0;
          var last_1 = (y2.length + shift | 0) - 1 | 0;
          if (inductionVariable_2 <= last_1)
            do {
              var i_2 = inductionVariable_2;
              inductionVariable_2 = inductionVariable_2 + 1 | 0;
              y2[i_2] = y2[i_2 - shift | 0];
            } while (!(i_2 === last_1));
          var inductionVariable_3 = y2.length + shift | 0;
          var last_2 = y2.length - 1 | 0;
          if (inductionVariable_3 <= last_2)
            do {
              var i_3 = inductionVariable_3;
              inductionVariable_3 = inductionVariable_3 + 1 | 0;
              y2[i_3] = 0;
            } while (!(i_3 === last_2));
        }
      };
      Companion.prototype.decimateArray = function(y2, decrate, ydecimated) {
        var tmp$ret$0;
        var tmp0_min = ydecimated.length;
        var tmp1_min = y2.length / decrate | 0;
        tmp$ret$0 = Math.min(tmp0_min, tmp1_min);
        var n2 = tmp$ret$0;
        var inductionVariable = 0;
        var last = n2 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            ydecimated[i] = y2[imul(i, decrate)];
          } while (!(i === last));
      };
      Companion.prototype.stretchArray = function(y2, rate, ystretched) {
        var tmp$ret$0;
        var tmp0_min = y2.length;
        var tmp1_min = ystretched.length / rate | 0;
        tmp$ret$0 = Math.min(tmp0_min, tmp1_min);
        var n2 = tmp$ret$0;
        var inductionVariable = 0;
        var last = ystretched.length;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            ystretched[i] = 0;
          } while (!(i === last));
        var inductionVariable_0 = 0;
        var last_0 = n2 - 1 | 0;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            ystretched[imul(i_0, rate)] = y2[i_0];
          } while (!(i_0 === last_0));
      };
      Companion.prototype.timesEqualsArray = function(y2, f) {
        var inductionVariable = 0;
        var last = y2.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp1_array = y2;
            var tmp2_index0 = i;
            tmp1_array[tmp2_index0] = tmp1_array[tmp2_index0] * f;
          } while (inductionVariable <= last);
      };
      Companion.prototype.padArray = function(y2, ypadded) {
        if (y2.length < ypadded.length) {
          var inductionVariable = 0;
          var last = y2.length;
          if (inductionVariable <= last)
            do {
              var i = inductionVariable;
              inductionVariable = inductionVariable + 1 | 0;
              ypadded[i] = y2[i];
            } while (!(i === last));
          var inductionVariable_0 = y2.length;
          var last_0 = ypadded.length;
          if (inductionVariable_0 <= last_0)
            do {
              var i_0 = inductionVariable_0;
              inductionVariable_0 = inductionVariable_0 + 1 | 0;
              ypadded[i_0] = 0;
            } while (!(i_0 === last_0));
        } else {
          var inductionVariable_1 = 0;
          var last_1 = ypadded.length;
          if (inductionVariable_1 <= last_1)
            do {
              var i_1 = inductionVariable_1;
              inductionVariable_1 = inductionVariable_1 + 1 | 0;
              ypadded[i_1] = y2[i_1];
            } while (!(i_1 === last_1));
        }
      };
      Companion.$metadata$ = objectMeta("Companion");
      var Companion_instance;
      function Companion_getInstance() {
        if (Companion_instance == null)
          new Companion();
        return Companion_instance;
      }
      Sequence2.prototype.set_array_tn1sl2_k$ = function(_set____db54di) {
        this.array_1 = _set____db54di;
      };
      Sequence2.prototype.get_array_iosoq8_k$ = function() {
        return this.array_1;
      };
      Sequence2.prototype.alias = function(N) {
        var newx = new Float32Array(N);
        Companion_getInstance().aliasArray(this.array_1, newx);
        this.array_1 = newx;
      };
      Sequence2.prototype.getForIndex = function(index) {
        var retval = 0;
        if (index >= 0 ? index < this.array_1.length : false)
          retval = this.array_1[index];
        return retval;
      };
      Sequence2.prototype.reverse = function() {
        Companion_getInstance().reverseArray(this.array_1);
      };
      Sequence2.prototype.rmean = function() {
        Companion_getInstance().rmeanArray(this.array_1);
      };
      Sequence2.prototype.circularShift = function(shift) {
        Companion_getInstance().circularShiftArray(this.array_1, shift);
      };
      Sequence2.prototype.zeroShift = function(shift) {
        Companion_getInstance().zeroShiftArray(this.array_1, shift);
      };
      Sequence2.prototype.decimate = function(decrate) {
        var tmp = new Float32Array(this.array_1.length / decrate | 0);
        Companion_getInstance().decimateArray(this.array_1, decrate, tmp);
        this.array_1 = tmp;
      };
      Sequence2.prototype.stretch = function(rate) {
        var tmp = new Float32Array(imul(this.array_1.length, rate));
        Companion_getInstance().stretchArray(this.array_1, rate, tmp);
        this.array_1 = tmp;
      };
      Sequence2.prototype.timesEquals = function(f) {
        Companion_getInstance().timesEqualsArray(this.array_1, f);
      };
      Sequence2.prototype.pad = function(n2) {
        if (n2 > this.array_1.length) {
          var tmp = new Float32Array(n2);
          Companion_getInstance().padArray(this.array_1, tmp);
          this.array_1 = tmp;
        }
      };
      function Sequence2() {
        Companion_getInstance();
      }
      Sequence2.$metadata$ = classMeta("Sequence");
      Object.defineProperty(Sequence2.prototype, "array", {
        configurable: true,
        get: Sequence2.prototype.get_array_iosoq8_k$,
        set: Sequence2.prototype.set_array_tn1sl2_k$
      });
      function Window_init_$Init$(w, $this) {
        Window2.call($this, w.length);
        var tmp = $this;
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = w;
        tmp$ret$1 = tmp$ret$0.slice();
        tmp.w_1 = tmp$ret$1;
        return $this;
      }
      function Window_fromArray(w) {
        return Window_init_$Init$(w, Object.create(Window2.prototype));
      }
      function Window2(N) {
        this.w_1 = new Float32Array(N);
      }
      Window2.prototype.set_w_6vu9ec_k$ = function(_set____db54di) {
        this.w_1 = _set____db54di;
      };
      Window2.prototype.get_w_1mhr66_k$ = function() {
        return this.w_1;
      };
      Window2.prototype.length = function() {
        return this.w_1.length;
      };
      Window2.prototype.timesEquals = function(x2) {
        if (!(x2.length === this.w_1.length))
          throw IllegalArgumentException_init_$Create$("Argument length does not match window length");
        var inductionVariable = 0;
        var last = this.w_1.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp1_array = this.w_1;
            var tmp2_index0 = i;
            tmp1_array[tmp2_index0] = tmp1_array[tmp2_index0] * x2[i];
          } while (inductionVariable <= last);
      };
      Window2.prototype.get_array_iosoq8_k$ = function() {
        var tmp$ret$1;
        var tmp0_copyOf = this.w_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_copyOf;
        tmp$ret$1 = tmp$ret$0.slice();
        return tmp$ret$1;
      };
      Window2.prototype.windowArray = function(x2, index, y2) {
        if (!(y2.length === this.w_1.length))
          throw IllegalArgumentException_init_$Create$("Destination array length does not match window length");
        var inductionVariable = 0;
        var last = this.w_1.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var j = index + i | 0;
            if (j >= 0 ? j < x2.length : false) {
              y2[i] = this.w_1[i] * x2[j];
            } else {
              y2[i] = 0;
            }
          } while (inductionVariable <= last);
      };
      Window2.$metadata$ = classMeta("Window");
      Object.defineProperty(Window2.prototype, "w", {
        configurable: true,
        get: Window2.prototype.get_w_1mhr66_k$,
        set: Window2.prototype.set_w_6vu9ec_k$
      });
      Object.defineProperty(Window2.prototype, "array", {
        configurable: true,
        get: Window2.prototype.get_array_iosoq8_k$
      });
      function _set_yr__dl8bxe($this, _set____db54di) {
        $this.yr_1 = _set____db54di;
      }
      function _get_yr__ndcfbm($this) {
        var tmp = $this.yr_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("yr");
        }
      }
      function _set_yi__dl8c55($this, _set____db54di) {
        $this.yi_1 = _set____db54di;
      }
      function _get_yi__ndcf3v($this) {
        var tmp = $this.yi_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("yi");
        }
      }
      function _set_arraysUnlinked__eskfgr($this, _set____db54di) {
        $this.arraysUnlinked_1 = _set____db54di;
      }
      function _get_arraysUnlinked__upg6gx($this) {
        return $this.arraysUnlinked_1;
      }
      function _set_c__db558i($this, _set____db54di) {
        $this.c_1 = _set____db54di;
      }
      function _get_c__7mloi6($this) {
        var tmp = $this.c_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("c");
        }
      }
      function _set_c3__dl8tqx($this, _set____db54di) {
        $this.c3__1 = _set____db54di;
      }
      function _get_c3__ndbxi3($this) {
        var tmp = $this.c3__1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("c3");
        }
      }
      function _set_s__db55ma($this, _set____db54di) {
        $this.s_1 = _set____db54di;
      }
      function _get_s__7mlovy($this) {
        var tmp = $this.s_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("s");
        }
      }
      function _set_s3__dl8hvt($this, _set____db54di) {
        $this.s3__1 = _set____db54di;
      }
      function _get_s3__ndc9d7($this) {
        var tmp = $this.s3__1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("s3");
        }
      }
      function _get_dft__e670yn($this) {
        return $this.dft_1;
      }
      function CDFT_init_$Init$(log2N, $this) {
        CDFT2.call($this);
        if (log2N < 3)
          throw IllegalArgumentException_init_$Create$("DFT size must be >= 8");
        $this.arraysUnlinked_1 = true;
        $this.log2N_1 = log2N;
        $this.N_1 = 1 << log2N;
        createTable($this);
        if (log2N === 3)
          $this.dft_1 = new CDFTsr8(0, 1, 0);
        else if (log2N === 4)
          $this.dft_1 = new CDFTsr16(0, 1, 0);
        else if (log2N >= 5) {
          $this.dft_1 = CDFTsr_init_$Create$(log2N, _get_c__7mloi6($this), _get_c3__ndbxi3($this), _get_s__7mlovy($this), _get_s3__ndc9d7($this));
        } else
          throw IllegalArgumentException_init_$Create$("unknown log2N size, must be >=3 but was: " + log2N);
        return $this;
      }
      function CDFT_ofLogSize(log2N) {
        return CDFT_init_$Init$(log2N, Object.create(CDFT2.prototype));
      }
      function CDFT_init_$Init$_0(xr, xi, yr, yi, log2N, $this) {
        CDFT_init_$Init$(log2N, $this);
        $this.yr_1 = yr;
        $this.yi_1 = yi;
        $this.dft_1.link(xr, xi, yr, yi);
        $this.arraysUnlinked_1 = false;
        return $this;
      }
      function CDFT_ofArrays(xr, xi, yr, yi, log2N) {
        return CDFT_init_$Init$_0(xr, xi, yr, yi, log2N, Object.create(CDFT2.prototype));
      }
      function createTable($this) {
        var N8 = $this.N_1 / 8 | 0;
        $this.c_1 = new Float32Array(N8);
        $this.c3__1 = new Float32Array(N8);
        $this.s_1 = new Float32Array(N8);
        $this.s3__1 = new Float32Array(N8);
        var inductionVariable = 0;
        var last = N8 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp = _get_c__7mloi6($this);
            var tmp$ret$0;
            var tmp0_cos = 2 * get_PI() * i / $this.N_1;
            tmp$ret$0 = Math.cos(tmp0_cos);
            tmp[i] = tmp$ret$0;
            var tmp_0 = _get_c3__ndbxi3($this);
            var tmp$ret$1;
            var tmp1_cos = 2 * get_PI() * 3 * i / $this.N_1;
            tmp$ret$1 = Math.cos(tmp1_cos);
            tmp_0[i] = tmp$ret$1;
            var tmp_1 = _get_s__7mlovy($this);
            var tmp$ret$2;
            var tmp2_sin = 2 * get_PI() * i / $this.N_1;
            tmp$ret$2 = Math.sin(tmp2_sin);
            tmp_1[i] = -tmp$ret$2;
            var tmp_2 = _get_s3__ndc9d7($this);
            var tmp$ret$3;
            var tmp3_sin = 2 * get_PI() * 3 * i / $this.N_1;
            tmp$ret$3 = Math.sin(tmp3_sin);
            tmp_2[i] = -tmp$ret$3;
          } while (!(i === last));
      }
      function Companion_0() {
        Companion_instance_0 = this;
      }
      Companion_0.prototype.dftProduct = function(Xr, Xi, Yr, Yi, sign) {
        if ((!(Xr.length === Yr.length) ? true : !(Xi.length === Yi.length)) ? true : !(Xr.length === Xi.length))
          throw IllegalArgumentException_init_$Create$("Transform array lengths are not equal");
        var tmp;
        var inductionVariable = 0;
        var last = Xr.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            tmp = Xr[i] * Yr[i] - sign * Xi[i] * Yi[i];
            Yi[i] = Xr[i] * Yi[i] + sign * Xi[i] * Yr[i];
            Yr[i] = tmp;
          } while (inductionVariable <= last);
      };
      Companion_0.$metadata$ = objectMeta("Companion");
      var Companion_instance_0;
      function Companion_getInstance_0() {
        if (Companion_instance_0 == null)
          new Companion_0();
        return Companion_instance_0;
      }
      CDFT2.prototype.get_N_1mhr51_k$ = function() {
        return this.N_1;
      };
      CDFT2.prototype.get_log2N_ius8zb_k$ = function() {
        return this.log2N_1;
      };
      CDFT2.prototype.evaluateCDFT = function(xr, xi, Xr, Xi) {
        this.yr_1 = Xr;
        this.yi_1 = Xi;
        this.dft_1.link(xr, xi, Xr, Xi);
        this.arraysUnlinked_1 = false;
        this.dft_1.evaluate_de95qg_k$();
      };
      CDFT2.prototype.evaluateInverseCDFT = function(Xr, Xi, xr, xi) {
        this.yr_1 = xr;
        this.yi_1 = xi;
        this.dft_1.link(Xr, Xi, xr, xi);
        this.arraysUnlinked_1 = false;
        this.evaluateInverse();
      };
      CDFT2.prototype.evaluate = function() {
        if (this.arraysUnlinked_1)
          throw IllegalStateException_init_$Create$("Sequence and transform arrays are not linked");
        this.dft_1.evaluate_de95qg_k$();
      };
      CDFT2.prototype.evaluateInverse = function() {
        if (this.arraysUnlinked_1)
          throw IllegalStateException_init_$Create$("Sequence and transform arrays are not linked");
        this.dft_1.evaluate_de95qg_k$();
        var scale = 1 / this.N_1;
        var N2 = this.N_1 / 2 | 0;
        var tmp0_array = _get_yr__ndcfbm(this);
        var tmp1_index0 = 0;
        tmp0_array[tmp1_index0] = tmp0_array[tmp1_index0] * scale;
        var tmp2_array = _get_yi__ndcf3v(this);
        var tmp3_index0 = 0;
        tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] * scale;
        var tmp4_array = _get_yr__ndcfbm(this);
        var tmp5_index0 = N2;
        tmp4_array[tmp5_index0] = tmp4_array[tmp5_index0] * scale;
        var tmp6_array = _get_yi__ndcf3v(this);
        var tmp7_index0 = N2;
        tmp6_array[tmp7_index0] = tmp6_array[tmp7_index0] * scale;
        var i = 1;
        var j = this.N_1 - 1 | 0;
        var tmp;
        while (i < j) {
          tmp = _get_yr__ndcfbm(this)[i];
          _get_yr__ndcfbm(this)[i] = _get_yr__ndcfbm(this)[j] * scale;
          _get_yr__ndcfbm(this)[j] = tmp * scale;
          tmp = _get_yi__ndcf3v(this)[i];
          _get_yi__ndcf3v(this)[i] = _get_yi__ndcf3v(this)[j] * scale;
          _get_yi__ndcf3v(this)[j] = tmp * scale;
          var tmp8 = i;
          i = tmp8 + 1 | 0;
          var tmp9 = j;
          j = tmp9 - 1 | 0;
        }
      };
      function CDFT2() {
        Companion_getInstance_0();
        this.arraysUnlinked_1 = false;
      }
      CDFT2.$metadata$ = classMeta("CDFT");
      function _get_SQRT2BY2__e8870e($this) {
        return $this.SQRT2BY2__1;
      }
      function _set_dft1__9lli48($this, _set____db54di) {
        $this.dft1__1 = _set____db54di;
      }
      function _get_dft1__d5dhpo($this) {
        return $this.dft1__1;
      }
      function _set_dft2__9lli53($this, _set____db54di) {
        $this.dft2__1 = _set____db54di;
      }
      function _get_dft2__d5dhqj($this) {
        return $this.dft2__1;
      }
      function _set_dft3__9lli5y($this, _set____db54di) {
        $this.dft3__1 = _set____db54di;
      }
      function _get_dft3__d5dhre($this) {
        return $this.dft3__1;
      }
      function _set_c__db558i_0($this, _set____db54di) {
        $this.c_1 = _set____db54di;
      }
      function _get_c__7mloi6_0($this) {
        return $this.c_1;
      }
      function _set_c3__dl8tqx_0($this, _set____db54di) {
        $this.c3__1 = _set____db54di;
      }
      function _get_c3__ndbxi3_0($this) {
        return $this.c3__1;
      }
      function _set_s__db55ma_0($this, _set____db54di) {
        $this.s_1 = _set____db54di;
      }
      function _get_s__7mlovy_0($this) {
        return $this.s_1;
      }
      function _set_s3__dl8hvt_0($this, _set____db54di) {
        $this.s3__1 = _set____db54di;
      }
      function _get_s3__ndc9d7_0($this) {
        return $this.s3__1;
      }
      function _set_f__db55b3($this, _set____db54di) {
        $this.f_1 = _set____db54di;
      }
      function _get_f__7mlokr($this) {
        return $this.f_1;
      }
      function _set_reflect__m3p5lk($this, _set____db54di) {
        $this.reflect_1 = _set____db54di;
      }
      function _get_reflect__nb6m0k($this) {
        return $this.reflect_1;
      }
      function CDFTsr_init_$Init$(m, c, c3, s2, s3, $this) {
        CDFTsr.call($this);
        $this.m_1 = m;
        $this.N_1 = 1 << m;
        $this.Ndiv8__1 = $this.N_1 / 8 | 0;
        $this.Ndiv4__1 = $this.N_1 / 4 | 0;
        $this.xoffset_1 = 0;
        $this.xstride_1 = 1;
        $this.outXoffset_1 = 0;
        $this.c_1 = c;
        $this.c3__1 = c3;
        $this.s_1 = s2;
        $this.s3__1 = s3;
        $this.f_1 = 1;
        $this.reflect_1 = imul(2, c.length);
        if (m > 6) {
          $this.dft1__1 = CDFTsr_init_$Create$_1($this, 0, 2, 0, m - 1 | 0);
          $this.dft2__1 = CDFTsr_init_$Create$_1($this, 1, 4, $this.N_1 / 2 | 0, m - 2 | 0);
          $this.dft3__1 = CDFTsr_init_$Create$_1($this, 3, 4, imul(3, $this.N_1) / 4 | 0, m - 2 | 0);
        } else if (m === 6) {
          $this.dft1__1 = CDFTsr_init_$Create$_1($this, 0, 2, 0, 5);
          $this.dft2__1 = new CDFTsr16(1, 4, $this.N_1 / 2 | 0);
          $this.dft3__1 = new CDFTsr16(3, 4, imul(3, $this.N_1) / 4 | 0);
        } else if (m === 5) {
          $this.dft1__1 = new CDFTsr16(0, 2, 0);
          $this.dft2__1 = new CDFTsr8(1, 4, $this.N_1 / 2 | 0);
          $this.dft3__1 = new CDFTsr8(3, 4, imul(3, $this.N_1) / 4 | 0);
        }
        return $this;
      }
      function CDFTsr_init_$Create$(m, c, c3, s2, s3) {
        return CDFTsr_init_$Init$(m, c, c3, s2, s3, Object.create(CDFTsr.prototype));
      }
      function CDFTsr_init_$Init$_0($this) {
        CDFTsr.call($this);
        $this.dft1__1 = null;
        $this.dft2__1 = null;
        $this.dft3__1 = null;
        return $this;
      }
      function CDFTsr_init_$Create$_0() {
        return CDFTsr_init_$Init$_0(Object.create(CDFTsr.prototype));
      }
      function CDFTsr_init_$Init$_1(parent, dataOffset, dataStride, transformOffset, m, $this) {
        CDFTsr.call($this);
        $this.c_1 = parent.c_1;
        $this.c3__1 = parent.c3__1;
        $this.s_1 = parent.s_1;
        $this.s3__1 = parent.s3__1;
        $this.m_1 = m;
        $this.N_1 = 1 << m;
        $this.Ndiv8__1 = $this.N_1 / 8 | 0;
        $this.Ndiv4__1 = $this.N_1 / 4 | 0;
        $this.xoffset_1 = dataOffset;
        $this.xstride_1 = dataStride;
        $this.outXoffset_1 = transformOffset;
        $this.f_1 = ensureNotNull($this.c_1).length / $this.Ndiv8__1 | 0;
        $this.reflect_1 = imul(2, ensureNotNull($this.c_1).length);
        if (m > 6) {
          $this.dft1__1 = CDFTsr_init_$Create$_1($this, dataOffset, imul(dataStride, 2), transformOffset, m - 1 | 0);
          $this.dft2__1 = CDFTsr_init_$Create$_1($this, dataOffset + dataStride | 0, imul(dataStride, 4), transformOffset + ($this.N_1 / 2 | 0) | 0, m - 2 | 0);
          $this.dft3__1 = CDFTsr_init_$Create$_1($this, dataOffset + imul(3, dataStride) | 0, imul(dataStride, 4), transformOffset + (imul(3, $this.N_1) / 4 | 0) | 0, m - 2 | 0);
        } else if (m === 6) {
          $this.dft1__1 = CDFTsr_init_$Create$_1($this, dataOffset, imul(dataStride, 2), transformOffset, 5);
          $this.dft2__1 = new CDFTsr16(dataOffset + dataStride | 0, imul(dataStride, 4), transformOffset + ($this.N_1 / 2 | 0) | 0);
          $this.dft3__1 = new CDFTsr16(dataOffset + imul(3, dataStride) | 0, imul(dataStride, 4), transformOffset + (imul(3, $this.N_1) / 4 | 0) | 0);
        } else if (m === 5) {
          $this.dft1__1 = new CDFTsr16(dataOffset, imul(dataStride, 2), transformOffset);
          $this.dft2__1 = new CDFTsr8(dataOffset + dataStride | 0, imul(dataStride, 4), transformOffset + ($this.N_1 / 2 | 0) | 0);
          $this.dft3__1 = new CDFTsr8(dataOffset + imul(3, dataStride) | 0, imul(dataStride, 4), transformOffset + (imul(3, $this.N_1) / 4 | 0) | 0);
        }
        return $this;
      }
      function CDFTsr_init_$Create$_1(parent, dataOffset, dataStride, transformOffset, m) {
        return CDFTsr_init_$Init$_1(parent, dataOffset, dataStride, transformOffset, m, Object.create(CDFTsr.prototype));
      }
      function Companion_1() {
        Companion_instance_1 = this;
        var tmp = this;
        var tmp$ret$0;
        tmp$ret$0 = Math.sqrt(2);
        tmp.SQRT2BY2__1 = tmp$ret$0 / 2;
      }
      Companion_1.$metadata$ = objectMeta("Companion");
      var Companion_instance_1;
      function Companion_getInstance_1() {
        if (Companion_instance_1 == null)
          new Companion_1();
        return Companion_instance_1;
      }
      CDFTsr.prototype.set_xr_n8tm33_k$ = function(_set____db54di) {
        this.xr_1 = _set____db54di;
      };
      CDFTsr.prototype.get_xr_kntnjx_k$ = function() {
        var tmp = this.xr_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("xr");
        }
      };
      CDFTsr.prototype.set_xi_41v7l4_k$ = function(_set____db54di) {
        this.xi_1 = _set____db54di;
      };
      CDFTsr.prototype.get_xi_kntnk6_k$ = function() {
        var tmp = this.xi_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("xi");
        }
      };
      CDFTsr.prototype.set_outXr_dvcqpn_k$ = function(_set____db54di) {
        this.outXr_1 = _set____db54di;
      };
      CDFTsr.prototype.get_outXr_iwjr9b_k$ = function() {
        var tmp = this.outXr_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("outXr");
        }
      };
      CDFTsr.prototype.set_outXi_dfc2yk_k$ = function(_set____db54di) {
        this.outXi_1 = _set____db54di;
      };
      CDFTsr.prototype.get_outXi_iwjr92_k$ = function() {
        var tmp = this.outXi_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("outXi");
        }
      };
      CDFTsr.prototype.set_xoffset_bd3wle_k$ = function(_set____db54di) {
        this.xoffset_1 = _set____db54di;
      };
      CDFTsr.prototype.get_xoffset_u1srtq_k$ = function() {
        return this.xoffset_1;
      };
      CDFTsr.prototype.set_xstride_i6zsu4_k$ = function(_set____db54di) {
        this.xstride_1 = _set____db54di;
      };
      CDFTsr.prototype.get_xstride_rxppjs_k$ = function() {
        return this.xstride_1;
      };
      CDFTsr.prototype.set_outXoffset_dyl9jq_k$ = function(_set____db54di) {
        this.outXoffset_1 = _set____db54di;
      };
      CDFTsr.prototype.get_outXoffset_tmu2xy_k$ = function() {
        return this.outXoffset_1;
      };
      CDFTsr.prototype.set_m_669hr4_k$ = function(_set____db54di) {
        this.m_1 = _set____db54di;
      };
      CDFTsr.prototype.get_m_1mhr5w_k$ = function() {
        return this.m_1;
      };
      CDFTsr.prototype.set_N_hmx2g1_k$ = function(_set____db54di) {
        this.N_1 = _set____db54di;
      };
      CDFTsr.prototype.get_N_1mhr51_k$ = function() {
        return this.N_1;
      };
      CDFTsr.prototype.set_Ndiv8_bunsfs_k$ = function(_set____db54di) {
        this.Ndiv8__1 = _set____db54di;
      };
      CDFTsr.prototype.get_Ndiv8_ie3hf0_k$ = function() {
        return this.Ndiv8__1;
      };
      CDFTsr.prototype.set_Ndiv4_spbccc_k$ = function(_set____db54di) {
        this.Ndiv4__1 = _set____db54di;
      };
      CDFTsr.prototype.get_Ndiv4_ie3hew_k$ = function() {
        return this.Ndiv4__1;
      };
      CDFTsr.prototype.link = function(xr, xi, Xr, Xi) {
        this.xr_1 = xr;
        this.xi_1 = xi;
        this.outXr_1 = Xr;
        this.outXi_1 = Xi;
        ensureNotNull(this.dft1__1).link(xr, xi, Xr, Xi);
        ensureNotNull(this.dft2__1).link(xr, xi, Xr, Xi);
        ensureNotNull(this.dft3__1).link(xr, xi, Xr, Xi);
      };
      CDFTsr.prototype.evaluate_de95qg_k$ = function() {
        var T1r;
        var T1i;
        var T3r;
        var T3i;
        var Rr;
        var Ri;
        var Sr;
        var Si;
        var Wr;
        var Wi;
        ensureNotNull(this.dft1__1).evaluate_de95qg_k$();
        ensureNotNull(this.dft2__1).evaluate_de95qg_k$();
        ensureNotNull(this.dft3__1).evaluate_de95qg_k$();
        var kp = this.outXoffset_1;
        var kpN4 = kp + this.Ndiv4__1 | 0;
        var kpN2 = kpN4 + this.Ndiv4__1 | 0;
        var kp3N4 = kpN2 + this.Ndiv4__1 | 0;
        Rr = this.get_outXr_iwjr9b_k$()[kpN2] + this.get_outXr_iwjr9b_k$()[kp3N4];
        Ri = this.get_outXi_iwjr92_k$()[kpN2] + this.get_outXi_iwjr92_k$()[kp3N4];
        Sr = this.get_outXi_iwjr92_k$()[kp3N4] - this.get_outXi_iwjr92_k$()[kpN2];
        Si = this.get_outXr_iwjr9b_k$()[kpN2] - this.get_outXr_iwjr9b_k$()[kp3N4];
        this.get_outXr_iwjr9b_k$()[kpN2] = this.get_outXr_iwjr9b_k$()[kp] - Rr;
        this.get_outXi_iwjr92_k$()[kpN2] = this.get_outXi_iwjr92_k$()[kp] - Ri;
        this.get_outXr_iwjr9b_k$()[kp3N4] = this.get_outXr_iwjr9b_k$()[kpN4] + Sr;
        this.get_outXi_iwjr92_k$()[kp3N4] = this.get_outXi_iwjr92_k$()[kpN4] + Si;
        var tmp0_array = this.get_outXr_iwjr9b_k$();
        var tmp1_index0 = kp;
        tmp0_array[tmp1_index0] = tmp0_array[tmp1_index0] + Rr;
        var tmp2_array = this.get_outXi_iwjr92_k$();
        var tmp3_index0 = kp;
        tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] + Ri;
        var tmp4_array = this.get_outXr_iwjr9b_k$();
        var tmp5_index0 = kpN4;
        tmp4_array[tmp5_index0] = tmp4_array[tmp5_index0] - Sr;
        var tmp6_array = this.get_outXi_iwjr92_k$();
        var tmp7_index0 = kpN4;
        tmp6_array[tmp7_index0] = tmp6_array[tmp7_index0] - Si;
        var fk;
        var inductionVariable = 1;
        var last = this.Ndiv8__1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var k = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            fk = imul(this.f_1, k);
            kp = k + this.outXoffset_1 | 0;
            kpN4 = kp + this.Ndiv4__1 | 0;
            kpN2 = kpN4 + this.Ndiv4__1 | 0;
            kp3N4 = kpN2 + this.Ndiv4__1 | 0;
            Wr = ensureNotNull(this.c_1)[fk];
            Wi = ensureNotNull(this.s_1)[fk];
            T1r = Wr * this.get_outXr_iwjr9b_k$()[kpN2] - Wi * this.get_outXi_iwjr92_k$()[kpN2];
            T1i = Wr * this.get_outXi_iwjr92_k$()[kpN2] + Wi * this.get_outXr_iwjr9b_k$()[kpN2];
            Wr = ensureNotNull(this.c3__1)[fk];
            Wi = ensureNotNull(this.s3__1)[fk];
            T3r = Wr * this.get_outXr_iwjr9b_k$()[kp3N4] - Wi * this.get_outXi_iwjr92_k$()[kp3N4];
            T3i = Wr * this.get_outXi_iwjr92_k$()[kp3N4] + Wi * this.get_outXr_iwjr9b_k$()[kp3N4];
            Rr = T1r + T3r;
            Ri = T1i + T3i;
            Sr = T3i - T1i;
            Si = T1r - T3r;
            this.get_outXr_iwjr9b_k$()[kpN2] = this.get_outXr_iwjr9b_k$()[kp] - Rr;
            this.get_outXi_iwjr92_k$()[kpN2] = this.get_outXi_iwjr92_k$()[kp] - Ri;
            this.get_outXr_iwjr9b_k$()[kp3N4] = this.get_outXr_iwjr9b_k$()[kpN4] + Sr;
            this.get_outXi_iwjr92_k$()[kp3N4] = this.get_outXi_iwjr92_k$()[kpN4] + Si;
            var tmp9_array = this.get_outXr_iwjr9b_k$();
            var tmp10_index0 = kp;
            tmp9_array[tmp10_index0] = tmp9_array[tmp10_index0] + Rr;
            var tmp11_array = this.get_outXi_iwjr92_k$();
            var tmp12_index0 = kp;
            tmp11_array[tmp12_index0] = tmp11_array[tmp12_index0] + Ri;
            var tmp13_array = this.get_outXr_iwjr9b_k$();
            var tmp14_index0 = kpN4;
            tmp13_array[tmp14_index0] = tmp13_array[tmp14_index0] - Sr;
            var tmp15_array = this.get_outXi_iwjr92_k$();
            var tmp16_index0 = kpN4;
            tmp15_array[tmp16_index0] = tmp15_array[tmp16_index0] - Si;
          } while (!(k === last));
        kp = this.Ndiv8__1 + this.outXoffset_1 | 0;
        kpN4 = kp + this.Ndiv4__1 | 0;
        kpN2 = kpN4 + this.Ndiv4__1 | 0;
        kp3N4 = kpN2 + this.Ndiv4__1 | 0;
        T1r = Companion_getInstance_1().SQRT2BY2__1 * (this.get_outXr_iwjr9b_k$()[kpN2] + this.get_outXi_iwjr92_k$()[kpN2]);
        T1i = Companion_getInstance_1().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[kpN2] - this.get_outXr_iwjr9b_k$()[kpN2]);
        T3r = Companion_getInstance_1().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[kp3N4] - this.get_outXr_iwjr9b_k$()[kp3N4]);
        T3i = -Companion_getInstance_1().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[kp3N4] + this.get_outXr_iwjr9b_k$()[kp3N4]);
        Rr = T1r + T3r;
        Ri = T1i + T3i;
        Sr = T3i - T1i;
        Si = T1r - T3r;
        this.get_outXr_iwjr9b_k$()[kpN2] = this.get_outXr_iwjr9b_k$()[kp] - Rr;
        this.get_outXi_iwjr92_k$()[kpN2] = this.get_outXi_iwjr92_k$()[kp] - Ri;
        this.get_outXr_iwjr9b_k$()[kp3N4] = this.get_outXr_iwjr9b_k$()[kpN4] + Sr;
        this.get_outXi_iwjr92_k$()[kp3N4] = this.get_outXi_iwjr92_k$()[kpN4] + Si;
        var tmp17_array = this.get_outXr_iwjr9b_k$();
        var tmp18_index0 = kp;
        tmp17_array[tmp18_index0] = tmp17_array[tmp18_index0] + Rr;
        var tmp19_array = this.get_outXi_iwjr92_k$();
        var tmp20_index0 = kp;
        tmp19_array[tmp20_index0] = tmp19_array[tmp20_index0] + Ri;
        var tmp21_array = this.get_outXr_iwjr9b_k$();
        var tmp22_index0 = kpN4;
        tmp21_array[tmp22_index0] = tmp21_array[tmp22_index0] - Sr;
        var tmp23_array = this.get_outXi_iwjr92_k$();
        var tmp24_index0 = kpN4;
        tmp23_array[tmp24_index0] = tmp23_array[tmp24_index0] - Si;
        var inductionVariable_0 = this.Ndiv8__1 + 1 | 0;
        var last_0 = this.Ndiv4__1 - 1 | 0;
        if (inductionVariable_0 <= last_0)
          do {
            var k_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            fk = this.reflect_1 - imul(this.f_1, k_0) | 0;
            kp = k_0 + this.outXoffset_1 | 0;
            kpN4 = kp + this.Ndiv4__1 | 0;
            kpN2 = kpN4 + this.Ndiv4__1 | 0;
            kp3N4 = kpN2 + this.Ndiv4__1 | 0;
            Wr = -ensureNotNull(this.s_1)[fk];
            Wi = -ensureNotNull(this.c_1)[fk];
            T1r = Wr * this.get_outXr_iwjr9b_k$()[kpN2] - Wi * this.get_outXi_iwjr92_k$()[kpN2];
            T1i = Wr * this.get_outXi_iwjr92_k$()[kpN2] + Wi * this.get_outXr_iwjr9b_k$()[kpN2];
            Wr = ensureNotNull(this.s3__1)[fk];
            Wi = ensureNotNull(this.c3__1)[fk];
            T3r = Wr * this.get_outXr_iwjr9b_k$()[kp3N4] - Wi * this.get_outXi_iwjr92_k$()[kp3N4];
            T3i = Wr * this.get_outXi_iwjr92_k$()[kp3N4] + Wi * this.get_outXr_iwjr9b_k$()[kp3N4];
            Rr = T1r + T3r;
            Ri = T1i + T3i;
            Sr = T3i - T1i;
            Si = T1r - T3r;
            this.get_outXr_iwjr9b_k$()[kpN2] = this.get_outXr_iwjr9b_k$()[kp] - Rr;
            this.get_outXi_iwjr92_k$()[kpN2] = this.get_outXi_iwjr92_k$()[kp] - Ri;
            this.get_outXr_iwjr9b_k$()[kp3N4] = this.get_outXr_iwjr9b_k$()[kpN4] + Sr;
            this.get_outXi_iwjr92_k$()[kp3N4] = this.get_outXi_iwjr92_k$()[kpN4] + Si;
            var tmp26_array = this.get_outXr_iwjr9b_k$();
            var tmp27_index0 = kp;
            tmp26_array[tmp27_index0] = tmp26_array[tmp27_index0] + Rr;
            var tmp28_array = this.get_outXi_iwjr92_k$();
            var tmp29_index0 = kp;
            tmp28_array[tmp29_index0] = tmp28_array[tmp29_index0] + Ri;
            var tmp30_array = this.get_outXr_iwjr9b_k$();
            var tmp31_index0 = kpN4;
            tmp30_array[tmp31_index0] = tmp30_array[tmp31_index0] - Sr;
            var tmp32_array = this.get_outXi_iwjr92_k$();
            var tmp33_index0 = kpN4;
            tmp32_array[tmp33_index0] = tmp32_array[tmp33_index0] - Si;
          } while (!(k_0 === last_0));
      };
      function CDFTsr() {
        Companion_getInstance_1();
        this.xoffset_1 = 0;
        this.xstride_1 = 0;
        this.outXoffset_1 = 0;
        this.m_1 = 0;
        this.N_1 = 0;
        this.Ndiv8__1 = 0;
        this.Ndiv4__1 = 0;
        this.dft1__1 = null;
        this.dft2__1 = null;
        this.dft3__1 = null;
        this.c_1 = null;
        this.c3__1 = null;
        this.s_1 = null;
        this.s3__1 = null;
        this.f_1 = 0;
        this.reflect_1 = 0;
      }
      CDFTsr.$metadata$ = classMeta("CDFTsr");
      function _get_n0__ndc5l5($this) {
        return $this.n0__1;
      }
      function _get_n1__ndc5m0($this) {
        return $this.n1__1;
      }
      function _get_n2__ndc5mv($this) {
        return $this.n2__1;
      }
      function _get_n3__ndc5nq($this) {
        return $this.n3__1;
      }
      function _get_n4__ndc5ol($this) {
        return $this.n4__1;
      }
      function _get_n5__ndc5pg($this) {
        return $this.n5__1;
      }
      function _get_n6__ndc5qb($this) {
        return $this.n6__1;
      }
      function _get_n7__ndc5r6($this) {
        return $this.n7__1;
      }
      function _get_n8__ndc5s1($this) {
        return $this.n8__1;
      }
      function _get_n9__ndc5sw($this) {
        return $this.n9__1;
      }
      function _get_n10__e6c9wk($this) {
        return $this.n10__1;
      }
      function _get_n11__e6c9xf($this) {
        return $this.n11__1;
      }
      function _get_n12__e6c9ya($this) {
        return $this.n12__1;
      }
      function _get_n13__e6c9z5($this) {
        return $this.n13__1;
      }
      function _get_n14__e6ca00($this) {
        return $this.n14__1;
      }
      function _get_n15__e6ca0v($this) {
        return $this.n15__1;
      }
      function _get_m0__ndc4ug($this) {
        return $this.m0__1;
      }
      function _get_m1__ndc4vb($this) {
        return $this.m1__1;
      }
      function _get_m2__ndc4w6($this) {
        return $this.m2__1;
      }
      function _get_m3__ndc4x1($this) {
        return $this.m3__1;
      }
      function _get_m4__ndc4xw($this) {
        return $this.m4__1;
      }
      function _get_m5__ndc4yr($this) {
        return $this.m5__1;
      }
      function _get_m6__ndc4zm($this) {
        return $this.m6__1;
      }
      function _get_m7__ndc50h($this) {
        return $this.m7__1;
      }
      function _get_m8__ndc51c($this) {
        return $this.m8__1;
      }
      function _get_m9__ndc527($this) {
        return $this.m9__1;
      }
      function _get_m10__e6bmx1($this) {
        return $this.m10__1;
      }
      function _get_m11__e6bmxw($this) {
        return $this.m11__1;
      }
      function _get_m12__e6bmyr($this) {
        return $this.m12__1;
      }
      function _get_m13__e6bmzm($this) {
        return $this.m13__1;
      }
      function _get_m14__e6bn0h($this) {
        return $this.m14__1;
      }
      function _get_m15__e6bn1c($this) {
        return $this.m15__1;
      }
      function Companion_2() {
        Companion_instance_2 = this;
        var tmp = this;
        var tmp$ret$0;
        var tmp0_cos = 2 * get_PI() / 16;
        tmp$ret$0 = Math.cos(tmp0_cos);
        tmp.C_1_16__1 = tmp$ret$0;
        var tmp_0 = this;
        var tmp$ret$1;
        var tmp0_cos_0 = 2 * get_PI() * 3 / 16;
        tmp$ret$1 = Math.cos(tmp0_cos_0);
        tmp_0.C_3_16__1 = tmp$ret$1;
        var tmp_1 = this;
        var tmp$ret$2;
        tmp$ret$2 = Math.sqrt(2);
        tmp_1.SQRT2BY2__1 = tmp$ret$2 / 2;
      }
      Companion_2.prototype.get_C_1_16_3f5hmw_k$ = function() {
        return this.C_1_16__1;
      };
      Companion_2.prototype.get_C_3_16_3f47nu_k$ = function() {
        return this.C_3_16__1;
      };
      Companion_2.prototype.get_SQRT2BY2_x1x4ni_k$ = function() {
        return this.SQRT2BY2__1;
      };
      Companion_2.$metadata$ = objectMeta("Companion");
      var Companion_instance_2;
      function Companion_getInstance_2() {
        if (Companion_instance_2 == null)
          new Companion_2();
        return Companion_instance_2;
      }
      function CDFTsr16(dataOffset, dataStride, transformOffset) {
        Companion_getInstance_2();
        CDFTsr_init_$Init$_0(this);
        this.m_1 = 4;
        this.N_1 = 16;
        this.xoffset_1 = dataOffset;
        this.xstride_1 = dataStride;
        this.outXoffset_1 = transformOffset;
        this.n0__1 = this.xoffset_1;
        this.n1__1 = this.n0__1 + this.xstride_1 | 0;
        this.n2__1 = this.n1__1 + this.xstride_1 | 0;
        this.n3__1 = this.n2__1 + this.xstride_1 | 0;
        this.n4__1 = this.n3__1 + this.xstride_1 | 0;
        this.n5__1 = this.n4__1 + this.xstride_1 | 0;
        this.n6__1 = this.n5__1 + this.xstride_1 | 0;
        this.n7__1 = this.n6__1 + this.xstride_1 | 0;
        this.n8__1 = this.n7__1 + this.xstride_1 | 0;
        this.n9__1 = this.n8__1 + this.xstride_1 | 0;
        this.n10__1 = this.n9__1 + this.xstride_1 | 0;
        this.n11__1 = this.n10__1 + this.xstride_1 | 0;
        this.n12__1 = this.n11__1 + this.xstride_1 | 0;
        this.n13__1 = this.n12__1 + this.xstride_1 | 0;
        this.n14__1 = this.n13__1 + this.xstride_1 | 0;
        this.n15__1 = this.n14__1 + this.xstride_1 | 0;
        this.m0__1 = this.outXoffset_1;
        this.m1__1 = this.m0__1 + 1 | 0;
        this.m2__1 = this.m1__1 + 1 | 0;
        this.m3__1 = this.m2__1 + 1 | 0;
        this.m4__1 = this.m3__1 + 1 | 0;
        this.m5__1 = this.m4__1 + 1 | 0;
        this.m6__1 = this.m5__1 + 1 | 0;
        this.m7__1 = this.m6__1 + 1 | 0;
        this.m8__1 = this.m7__1 + 1 | 0;
        this.m9__1 = this.m8__1 + 1 | 0;
        this.m10__1 = this.m9__1 + 1 | 0;
        this.m11__1 = this.m10__1 + 1 | 0;
        this.m12__1 = this.m11__1 + 1 | 0;
        this.m13__1 = this.m12__1 + 1 | 0;
        this.m14__1 = this.m13__1 + 1 | 0;
        this.m15__1 = this.m14__1 + 1 | 0;
      }
      CDFTsr16.prototype.link_unhtbf_k$ = function(xr, xi, Xr, Xi) {
        this.xr_1 = xr;
        this.xi_1 = xi;
        this.outXr_1 = Xr;
        this.outXi_1 = Xi;
      };
      CDFTsr16.prototype.link = function(xr, xi, Xr, Xi) {
        return this.link_unhtbf_k$(xr, xi, Xr, Xi);
      };
      CDFTsr16.prototype.evaluate_de95qg_k$ = function() {
        var T1r;
        var T1i;
        var T3r;
        var T3i;
        var Rr;
        var Ri;
        var Sr;
        var Si;
        this.get_outXr_iwjr9b_k$()[this.m0__1] = this.get_xr_kntnjx_k$()[this.n0__1] + this.get_xr_kntnjx_k$()[this.n8__1];
        this.get_outXi_iwjr92_k$()[this.m0__1] = this.get_xi_kntnk6_k$()[this.n0__1] + this.get_xi_kntnk6_k$()[this.n8__1];
        this.get_outXr_iwjr9b_k$()[this.m1__1] = this.get_xr_kntnjx_k$()[this.n0__1] - this.get_xr_kntnjx_k$()[this.n8__1];
        this.get_outXi_iwjr92_k$()[this.m1__1] = this.get_xi_kntnk6_k$()[this.n0__1] - this.get_xi_kntnk6_k$()[this.n8__1];
        Rr = this.get_xr_kntnjx_k$()[this.n4__1] + this.get_xr_kntnjx_k$()[this.n12__1];
        Ri = this.get_xi_kntnk6_k$()[this.n4__1] + this.get_xi_kntnk6_k$()[this.n12__1];
        Sr = this.get_xi_kntnk6_k$()[this.n12__1] - this.get_xi_kntnk6_k$()[this.n4__1];
        Si = this.get_xr_kntnjx_k$()[this.n4__1] - this.get_xr_kntnjx_k$()[this.n12__1];
        this.get_outXr_iwjr9b_k$()[this.m2__1] = this.get_outXr_iwjr9b_k$()[this.m0__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m2__1] = this.get_outXi_iwjr92_k$()[this.m0__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m3__1] = this.get_outXr_iwjr9b_k$()[this.m1__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m3__1] = this.get_outXi_iwjr92_k$()[this.m1__1] + Si;
        var tmp0_array = this.get_outXr_iwjr9b_k$();
        var tmp1_index0 = this.m0__1;
        tmp0_array[tmp1_index0] = tmp0_array[tmp1_index0] + Rr;
        var tmp2_array = this.get_outXi_iwjr92_k$();
        var tmp3_index0 = this.m0__1;
        tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] + Ri;
        var tmp4_array = this.get_outXr_iwjr9b_k$();
        var tmp5_index0 = this.m1__1;
        tmp4_array[tmp5_index0] = tmp4_array[tmp5_index0] - Sr;
        var tmp6_array = this.get_outXi_iwjr92_k$();
        var tmp7_index0 = this.m1__1;
        tmp6_array[tmp7_index0] = tmp6_array[tmp7_index0] - Si;
        this.get_outXr_iwjr9b_k$()[this.m4__1] = this.get_xr_kntnjx_k$()[this.n2__1] + this.get_xr_kntnjx_k$()[this.n10__1];
        this.get_outXi_iwjr92_k$()[this.m4__1] = this.get_xi_kntnk6_k$()[this.n2__1] + this.get_xi_kntnk6_k$()[this.n10__1];
        this.get_outXr_iwjr9b_k$()[this.m5__1] = this.get_xr_kntnjx_k$()[this.n2__1] - this.get_xr_kntnjx_k$()[this.n10__1];
        this.get_outXi_iwjr92_k$()[this.m5__1] = this.get_xi_kntnk6_k$()[this.n2__1] - this.get_xi_kntnk6_k$()[this.n10__1];
        this.get_outXr_iwjr9b_k$()[this.m6__1] = this.get_xr_kntnjx_k$()[this.n6__1] + this.get_xr_kntnjx_k$()[this.n14__1];
        this.get_outXi_iwjr92_k$()[this.m6__1] = this.get_xi_kntnk6_k$()[this.n6__1] + this.get_xi_kntnk6_k$()[this.n14__1];
        this.get_outXr_iwjr9b_k$()[this.m7__1] = this.get_xr_kntnjx_k$()[this.n6__1] - this.get_xr_kntnjx_k$()[this.n14__1];
        this.get_outXi_iwjr92_k$()[this.m7__1] = this.get_xi_kntnk6_k$()[this.n6__1] - this.get_xi_kntnk6_k$()[this.n14__1];
        Rr = this.get_outXr_iwjr9b_k$()[this.m4__1] + this.get_outXr_iwjr9b_k$()[this.m6__1];
        Ri = this.get_outXi_iwjr92_k$()[this.m4__1] + this.get_outXi_iwjr92_k$()[this.m6__1];
        Sr = this.get_outXi_iwjr92_k$()[this.m6__1] - this.get_outXi_iwjr92_k$()[this.m4__1];
        Si = this.get_outXr_iwjr9b_k$()[this.m4__1] - this.get_outXr_iwjr9b_k$()[this.m6__1];
        this.get_outXr_iwjr9b_k$()[this.m4__1] = this.get_outXr_iwjr9b_k$()[this.m0__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m4__1] = this.get_outXi_iwjr92_k$()[this.m0__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m6__1] = this.get_outXr_iwjr9b_k$()[this.m2__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m6__1] = this.get_outXi_iwjr92_k$()[this.m2__1] + Si;
        var tmp8_array = this.get_outXr_iwjr9b_k$();
        var tmp9_index0 = this.m0__1;
        tmp8_array[tmp9_index0] = tmp8_array[tmp9_index0] + Rr;
        var tmp10_array = this.get_outXi_iwjr92_k$();
        var tmp11_index0 = this.m0__1;
        tmp10_array[tmp11_index0] = tmp10_array[tmp11_index0] + Ri;
        var tmp12_array = this.get_outXr_iwjr9b_k$();
        var tmp13_index0 = this.m2__1;
        tmp12_array[tmp13_index0] = tmp12_array[tmp13_index0] - Sr;
        var tmp14_array = this.get_outXi_iwjr92_k$();
        var tmp15_index0 = this.m2__1;
        tmp14_array[tmp15_index0] = tmp14_array[tmp15_index0] - Si;
        T1r = Companion_getInstance_2().SQRT2BY2__1 * (this.get_outXr_iwjr9b_k$()[this.m5__1] + this.get_outXi_iwjr92_k$()[this.m5__1]);
        T1i = Companion_getInstance_2().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[this.m5__1] - this.get_outXr_iwjr9b_k$()[this.m5__1]);
        T3r = Companion_getInstance_2().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[this.m7__1] - this.get_outXr_iwjr9b_k$()[this.m7__1]);
        T3i = -Companion_getInstance_2().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[this.m7__1] + this.get_outXr_iwjr9b_k$()[this.m7__1]);
        Rr = T1r + T3r;
        Ri = T1i + T3i;
        Sr = T3i - T1i;
        Si = T1r - T3r;
        this.get_outXr_iwjr9b_k$()[this.m5__1] = this.get_outXr_iwjr9b_k$()[this.m1__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m5__1] = this.get_outXi_iwjr92_k$()[this.m1__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m7__1] = this.get_outXr_iwjr9b_k$()[this.m3__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m7__1] = this.get_outXi_iwjr92_k$()[this.m3__1] + Si;
        var tmp16_array = this.get_outXr_iwjr9b_k$();
        var tmp17_index0 = this.m1__1;
        tmp16_array[tmp17_index0] = tmp16_array[tmp17_index0] + Rr;
        var tmp18_array = this.get_outXi_iwjr92_k$();
        var tmp19_index0 = this.m1__1;
        tmp18_array[tmp19_index0] = tmp18_array[tmp19_index0] + Ri;
        var tmp20_array = this.get_outXr_iwjr9b_k$();
        var tmp21_index0 = this.m3__1;
        tmp20_array[tmp21_index0] = tmp20_array[tmp21_index0] - Sr;
        var tmp22_array = this.get_outXi_iwjr92_k$();
        var tmp23_index0 = this.m3__1;
        tmp22_array[tmp23_index0] = tmp22_array[tmp23_index0] - Si;
        this.get_outXr_iwjr9b_k$()[this.m8__1] = this.get_xr_kntnjx_k$()[this.n1__1] + this.get_xr_kntnjx_k$()[this.n9__1];
        this.get_outXi_iwjr92_k$()[this.m8__1] = this.get_xi_kntnk6_k$()[this.n1__1] + this.get_xi_kntnk6_k$()[this.n9__1];
        this.get_outXr_iwjr9b_k$()[this.m9__1] = this.get_xr_kntnjx_k$()[this.n1__1] - this.get_xr_kntnjx_k$()[this.n9__1];
        this.get_outXi_iwjr92_k$()[this.m9__1] = this.get_xi_kntnk6_k$()[this.n1__1] - this.get_xi_kntnk6_k$()[this.n9__1];
        Rr = this.get_xr_kntnjx_k$()[this.n5__1] + this.get_xr_kntnjx_k$()[this.n13__1];
        Ri = this.get_xi_kntnk6_k$()[this.n5__1] + this.get_xi_kntnk6_k$()[this.n13__1];
        Sr = this.get_xi_kntnk6_k$()[this.n13__1] - this.get_xi_kntnk6_k$()[this.n5__1];
        Si = this.get_xr_kntnjx_k$()[this.n5__1] - this.get_xr_kntnjx_k$()[this.n13__1];
        this.get_outXr_iwjr9b_k$()[this.m10__1] = this.get_outXr_iwjr9b_k$()[this.m8__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m10__1] = this.get_outXi_iwjr92_k$()[this.m8__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m11__1] = this.get_outXr_iwjr9b_k$()[this.m9__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m11__1] = this.get_outXi_iwjr92_k$()[this.m9__1] + Si;
        var tmp24_array = this.get_outXr_iwjr9b_k$();
        var tmp25_index0 = this.m8__1;
        tmp24_array[tmp25_index0] = tmp24_array[tmp25_index0] + Rr;
        var tmp26_array = this.get_outXi_iwjr92_k$();
        var tmp27_index0 = this.m8__1;
        tmp26_array[tmp27_index0] = tmp26_array[tmp27_index0] + Ri;
        var tmp28_array = this.get_outXr_iwjr9b_k$();
        var tmp29_index0 = this.m9__1;
        tmp28_array[tmp29_index0] = tmp28_array[tmp29_index0] - Sr;
        var tmp30_array = this.get_outXi_iwjr92_k$();
        var tmp31_index0 = this.m9__1;
        tmp30_array[tmp31_index0] = tmp30_array[tmp31_index0] - Si;
        this.get_outXr_iwjr9b_k$()[this.m12__1] = this.get_xr_kntnjx_k$()[this.n3__1] + this.get_xr_kntnjx_k$()[this.n11__1];
        this.get_outXi_iwjr92_k$()[this.m12__1] = this.get_xi_kntnk6_k$()[this.n3__1] + this.get_xi_kntnk6_k$()[this.n11__1];
        this.get_outXr_iwjr9b_k$()[this.m13__1] = this.get_xr_kntnjx_k$()[this.n3__1] - this.get_xr_kntnjx_k$()[this.n11__1];
        this.get_outXi_iwjr92_k$()[this.m13__1] = this.get_xi_kntnk6_k$()[this.n3__1] - this.get_xi_kntnk6_k$()[this.n11__1];
        Rr = this.get_xr_kntnjx_k$()[this.n7__1] + this.get_xr_kntnjx_k$()[this.n15__1];
        Ri = this.get_xi_kntnk6_k$()[this.n7__1] + this.get_xi_kntnk6_k$()[this.n15__1];
        Sr = this.get_xi_kntnk6_k$()[this.n15__1] - this.get_xi_kntnk6_k$()[this.n7__1];
        Si = this.get_xr_kntnjx_k$()[this.n7__1] - this.get_xr_kntnjx_k$()[this.n15__1];
        this.get_outXr_iwjr9b_k$()[this.m14__1] = this.get_outXr_iwjr9b_k$()[this.m12__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m14__1] = this.get_outXi_iwjr92_k$()[this.m12__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m15__1] = this.get_outXr_iwjr9b_k$()[this.m13__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m15__1] = this.get_outXi_iwjr92_k$()[this.m13__1] + Si;
        var tmp32_array = this.get_outXr_iwjr9b_k$();
        var tmp33_index0 = this.m12__1;
        tmp32_array[tmp33_index0] = tmp32_array[tmp33_index0] + Rr;
        var tmp34_array = this.get_outXi_iwjr92_k$();
        var tmp35_index0 = this.m12__1;
        tmp34_array[tmp35_index0] = tmp34_array[tmp35_index0] + Ri;
        var tmp36_array = this.get_outXr_iwjr9b_k$();
        var tmp37_index0 = this.m13__1;
        tmp36_array[tmp37_index0] = tmp36_array[tmp37_index0] - Sr;
        var tmp38_array = this.get_outXi_iwjr92_k$();
        var tmp39_index0 = this.m13__1;
        tmp38_array[tmp39_index0] = tmp38_array[tmp39_index0] - Si;
        Rr = this.get_outXr_iwjr9b_k$()[this.m8__1] + this.get_outXr_iwjr9b_k$()[this.m12__1];
        Ri = this.get_outXi_iwjr92_k$()[this.m8__1] + this.get_outXi_iwjr92_k$()[this.m12__1];
        Sr = this.get_outXi_iwjr92_k$()[this.m12__1] - this.get_outXi_iwjr92_k$()[this.m8__1];
        Si = this.get_outXr_iwjr9b_k$()[this.m8__1] - this.get_outXr_iwjr9b_k$()[this.m12__1];
        this.get_outXr_iwjr9b_k$()[this.m8__1] = this.get_outXr_iwjr9b_k$()[this.m0__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m8__1] = this.get_outXi_iwjr92_k$()[this.m0__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m12__1] = this.get_outXr_iwjr9b_k$()[this.m4__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m12__1] = this.get_outXi_iwjr92_k$()[this.m4__1] + Si;
        var tmp40_array = this.get_outXr_iwjr9b_k$();
        var tmp41_index0 = this.m0__1;
        tmp40_array[tmp41_index0] = tmp40_array[tmp41_index0] + Rr;
        var tmp42_array = this.get_outXi_iwjr92_k$();
        var tmp43_index0 = this.m0__1;
        tmp42_array[tmp43_index0] = tmp42_array[tmp43_index0] + Ri;
        var tmp44_array = this.get_outXr_iwjr9b_k$();
        var tmp45_index0 = this.m4__1;
        tmp44_array[tmp45_index0] = tmp44_array[tmp45_index0] - Sr;
        var tmp46_array = this.get_outXi_iwjr92_k$();
        var tmp47_index0 = this.m4__1;
        tmp46_array[tmp47_index0] = tmp46_array[tmp47_index0] - Si;
        T1r = Companion_getInstance_2().C_1_16__1 * this.get_outXr_iwjr9b_k$()[this.m9__1] + Companion_getInstance_2().C_3_16__1 * this.get_outXi_iwjr92_k$()[this.m9__1];
        T1i = Companion_getInstance_2().C_1_16__1 * this.get_outXi_iwjr92_k$()[this.m9__1] - Companion_getInstance_2().C_3_16__1 * this.get_outXr_iwjr9b_k$()[this.m9__1];
        T3r = Companion_getInstance_2().C_3_16__1 * this.get_outXr_iwjr9b_k$()[this.m13__1] + Companion_getInstance_2().C_1_16__1 * this.get_outXi_iwjr92_k$()[this.m13__1];
        T3i = Companion_getInstance_2().C_3_16__1 * this.get_outXi_iwjr92_k$()[this.m13__1] - Companion_getInstance_2().C_1_16__1 * this.get_outXr_iwjr9b_k$()[this.m13__1];
        Rr = T1r + T3r;
        Ri = T1i + T3i;
        Sr = T3i - T1i;
        Si = T1r - T3r;
        this.get_outXr_iwjr9b_k$()[this.m9__1] = this.get_outXr_iwjr9b_k$()[this.m1__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m9__1] = this.get_outXi_iwjr92_k$()[this.m1__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m13__1] = this.get_outXr_iwjr9b_k$()[this.m5__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m13__1] = this.get_outXi_iwjr92_k$()[this.m5__1] + Si;
        var tmp48_array = this.get_outXr_iwjr9b_k$();
        var tmp49_index0 = this.m1__1;
        tmp48_array[tmp49_index0] = tmp48_array[tmp49_index0] + Rr;
        var tmp50_array = this.get_outXi_iwjr92_k$();
        var tmp51_index0 = this.m1__1;
        tmp50_array[tmp51_index0] = tmp50_array[tmp51_index0] + Ri;
        var tmp52_array = this.get_outXr_iwjr9b_k$();
        var tmp53_index0 = this.m5__1;
        tmp52_array[tmp53_index0] = tmp52_array[tmp53_index0] - Sr;
        var tmp54_array = this.get_outXi_iwjr92_k$();
        var tmp55_index0 = this.m5__1;
        tmp54_array[tmp55_index0] = tmp54_array[tmp55_index0] - Si;
        T1r = Companion_getInstance_2().SQRT2BY2__1 * (this.get_outXr_iwjr9b_k$()[this.m10__1] + this.get_outXi_iwjr92_k$()[this.m10__1]);
        T1i = Companion_getInstance_2().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[this.m10__1] - this.get_outXr_iwjr9b_k$()[this.m10__1]);
        T3r = Companion_getInstance_2().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[this.m14__1] - this.get_outXr_iwjr9b_k$()[this.m14__1]);
        T3i = -Companion_getInstance_2().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[this.m14__1] + this.get_outXr_iwjr9b_k$()[this.m14__1]);
        Rr = T1r + T3r;
        Ri = T1i + T3i;
        Sr = T3i - T1i;
        Si = T1r - T3r;
        this.get_outXr_iwjr9b_k$()[this.m10__1] = this.get_outXr_iwjr9b_k$()[this.m2__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m10__1] = this.get_outXi_iwjr92_k$()[this.m2__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m14__1] = this.get_outXr_iwjr9b_k$()[this.m6__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m14__1] = this.get_outXi_iwjr92_k$()[this.m6__1] + Si;
        var tmp56_array = this.get_outXr_iwjr9b_k$();
        var tmp57_index0 = this.m2__1;
        tmp56_array[tmp57_index0] = tmp56_array[tmp57_index0] + Rr;
        var tmp58_array = this.get_outXi_iwjr92_k$();
        var tmp59_index0 = this.m2__1;
        tmp58_array[tmp59_index0] = tmp58_array[tmp59_index0] + Ri;
        var tmp60_array = this.get_outXr_iwjr9b_k$();
        var tmp61_index0 = this.m6__1;
        tmp60_array[tmp61_index0] = tmp60_array[tmp61_index0] - Sr;
        var tmp62_array = this.get_outXi_iwjr92_k$();
        var tmp63_index0 = this.m6__1;
        tmp62_array[tmp63_index0] = tmp62_array[tmp63_index0] - Si;
        T1r = Companion_getInstance_2().C_3_16__1 * this.get_outXr_iwjr9b_k$()[this.m11__1] + Companion_getInstance_2().C_1_16__1 * this.get_outXi_iwjr92_k$()[this.m11__1];
        T1i = Companion_getInstance_2().C_3_16__1 * this.get_outXi_iwjr92_k$()[this.m11__1] - Companion_getInstance_2().C_1_16__1 * this.get_outXr_iwjr9b_k$()[this.m11__1];
        T3r = -Companion_getInstance_2().C_1_16__1 * this.get_outXr_iwjr9b_k$()[this.m15__1] - Companion_getInstance_2().C_3_16__1 * this.get_outXi_iwjr92_k$()[this.m15__1];
        T3i = -Companion_getInstance_2().C_1_16__1 * this.get_outXi_iwjr92_k$()[this.m15__1] + Companion_getInstance_2().C_3_16__1 * this.get_outXr_iwjr9b_k$()[this.m15__1];
        Rr = T1r + T3r;
        Ri = T1i + T3i;
        Sr = T3i - T1i;
        Si = T1r - T3r;
        this.get_outXr_iwjr9b_k$()[this.m11__1] = this.get_outXr_iwjr9b_k$()[this.m3__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m11__1] = this.get_outXi_iwjr92_k$()[this.m3__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m15__1] = this.get_outXr_iwjr9b_k$()[this.m7__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m15__1] = this.get_outXi_iwjr92_k$()[this.m7__1] + Si;
        var tmp64_array = this.get_outXr_iwjr9b_k$();
        var tmp65_index0 = this.m3__1;
        tmp64_array[tmp65_index0] = tmp64_array[tmp65_index0] + Rr;
        var tmp66_array = this.get_outXi_iwjr92_k$();
        var tmp67_index0 = this.m3__1;
        tmp66_array[tmp67_index0] = tmp66_array[tmp67_index0] + Ri;
        var tmp68_array = this.get_outXr_iwjr9b_k$();
        var tmp69_index0 = this.m7__1;
        tmp68_array[tmp69_index0] = tmp68_array[tmp69_index0] - Sr;
        var tmp70_array = this.get_outXi_iwjr92_k$();
        var tmp71_index0 = this.m7__1;
        tmp70_array[tmp71_index0] = tmp70_array[tmp71_index0] - Si;
      };
      CDFTsr16.$metadata$ = classMeta("CDFTsr16", void 0, void 0, void 0, void 0, CDFTsr.prototype);
      function _get_n0__ndc5l5_0($this) {
        return $this.n0__1;
      }
      function _get_m0__ndc4ug_0($this) {
        return $this.m0__1;
      }
      function _get_n1__ndc5m0_0($this) {
        return $this.n1__1;
      }
      function _get_n2__ndc5mv_0($this) {
        return $this.n2__1;
      }
      function _get_n3__ndc5nq_0($this) {
        return $this.n3__1;
      }
      function _get_n4__ndc5ol_0($this) {
        return $this.n4__1;
      }
      function _get_n5__ndc5pg_0($this) {
        return $this.n5__1;
      }
      function _get_n6__ndc5qb_0($this) {
        return $this.n6__1;
      }
      function _get_n7__ndc5r6_0($this) {
        return $this.n7__1;
      }
      function _get_m1__ndc4vb_0($this) {
        return $this.m1__1;
      }
      function _get_m2__ndc4w6_0($this) {
        return $this.m2__1;
      }
      function _get_m3__ndc4x1_0($this) {
        return $this.m3__1;
      }
      function _get_m4__ndc4xw_0($this) {
        return $this.m4__1;
      }
      function _get_m5__ndc4yr_0($this) {
        return $this.m5__1;
      }
      function _get_m6__ndc4zm_0($this) {
        return $this.m6__1;
      }
      function _get_m7__ndc50h_0($this) {
        return $this.m7__1;
      }
      function Companion_3() {
        Companion_instance_3 = this;
        var tmp = this;
        var tmp$ret$0;
        tmp$ret$0 = Math.sqrt(2);
        tmp.SQRT2BY2__1 = tmp$ret$0 / 2;
      }
      Companion_3.prototype.get_SQRT2BY2_x1x4ni_k$ = function() {
        return this.SQRT2BY2__1;
      };
      Companion_3.$metadata$ = objectMeta("Companion");
      var Companion_instance_3;
      function Companion_getInstance_3() {
        if (Companion_instance_3 == null)
          new Companion_3();
        return Companion_instance_3;
      }
      function CDFTsr8(n0, xstride, m0) {
        Companion_getInstance_3();
        CDFTsr_init_$Init$_0(this);
        this.n0__1 = n0;
        this.m0__1 = m0;
        this.m_1 = 3;
        this.N_1 = 8;
        this.xoffset_1 = this.n0__1;
        this.xstride_1 = xstride;
        this.outXoffset_1 = this.m0__1;
        this.n1__1 = this.n0__1 + xstride | 0;
        this.n2__1 = this.n1__1 + xstride | 0;
        this.n3__1 = this.n2__1 + xstride | 0;
        this.n4__1 = this.n3__1 + xstride | 0;
        this.n5__1 = this.n4__1 + xstride | 0;
        this.n6__1 = this.n5__1 + xstride | 0;
        this.n7__1 = this.n6__1 + xstride | 0;
        this.m1__1 = this.m0__1 + 1 | 0;
        this.m2__1 = this.m1__1 + 1 | 0;
        this.m3__1 = this.m2__1 + 1 | 0;
        this.m4__1 = this.m3__1 + 1 | 0;
        this.m5__1 = this.m4__1 + 1 | 0;
        this.m6__1 = this.m5__1 + 1 | 0;
        this.m7__1 = this.m6__1 + 1 | 0;
      }
      CDFTsr8.prototype.link_unhtbf_k$ = function(xr, xi, Xr, Xi) {
        this.xr_1 = xr;
        this.xi_1 = xi;
        this.outXr_1 = Xr;
        this.outXi_1 = Xi;
      };
      CDFTsr8.prototype.link = function(xr, xi, Xr, Xi) {
        return this.link_unhtbf_k$(xr, xi, Xr, Xi);
      };
      CDFTsr8.prototype.evaluate_de95qg_k$ = function() {
        var T1r;
        var T1i;
        var T3r;
        var T3i;
        var Rr;
        var Ri;
        var Sr;
        var Si;
        this.get_outXr_iwjr9b_k$()[this.m0__1] = this.get_xr_kntnjx_k$()[this.n0__1] + this.get_xr_kntnjx_k$()[this.n4__1];
        this.get_outXi_iwjr92_k$()[this.m0__1] = this.get_xi_kntnk6_k$()[this.n0__1] + this.get_xi_kntnk6_k$()[this.n4__1];
        this.get_outXr_iwjr9b_k$()[this.m1__1] = this.get_xr_kntnjx_k$()[this.n0__1] - this.get_xr_kntnjx_k$()[this.n4__1];
        this.get_outXi_iwjr92_k$()[this.m1__1] = this.get_xi_kntnk6_k$()[this.n0__1] - this.get_xi_kntnk6_k$()[this.n4__1];
        Rr = this.get_xr_kntnjx_k$()[this.n2__1] + this.get_xr_kntnjx_k$()[this.n6__1];
        Ri = this.get_xi_kntnk6_k$()[this.n2__1] + this.get_xi_kntnk6_k$()[this.n6__1];
        Sr = this.get_xi_kntnk6_k$()[this.n6__1] - this.get_xi_kntnk6_k$()[this.n2__1];
        Si = this.get_xr_kntnjx_k$()[this.n2__1] - this.get_xr_kntnjx_k$()[this.n6__1];
        this.get_outXr_iwjr9b_k$()[this.m2__1] = this.get_outXr_iwjr9b_k$()[this.m0__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m2__1] = this.get_outXi_iwjr92_k$()[this.m0__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m3__1] = this.get_outXr_iwjr9b_k$()[this.m1__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m3__1] = this.get_outXi_iwjr92_k$()[this.m1__1] + Si;
        var tmp0_array = this.get_outXr_iwjr9b_k$();
        var tmp1_index0 = this.m0__1;
        tmp0_array[tmp1_index0] = tmp0_array[tmp1_index0] + Rr;
        var tmp2_array = this.get_outXi_iwjr92_k$();
        var tmp3_index0 = this.m0__1;
        tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] + Ri;
        var tmp4_array = this.get_outXr_iwjr9b_k$();
        var tmp5_index0 = this.m1__1;
        tmp4_array[tmp5_index0] = tmp4_array[tmp5_index0] - Sr;
        var tmp6_array = this.get_outXi_iwjr92_k$();
        var tmp7_index0 = this.m1__1;
        tmp6_array[tmp7_index0] = tmp6_array[tmp7_index0] - Si;
        this.get_outXr_iwjr9b_k$()[this.m4__1] = this.get_xr_kntnjx_k$()[this.n1__1] + this.get_xr_kntnjx_k$()[this.n5__1];
        this.get_outXi_iwjr92_k$()[this.m4__1] = this.get_xi_kntnk6_k$()[this.n1__1] + this.get_xi_kntnk6_k$()[this.n5__1];
        this.get_outXr_iwjr9b_k$()[this.m5__1] = this.get_xr_kntnjx_k$()[this.n1__1] - this.get_xr_kntnjx_k$()[this.n5__1];
        this.get_outXi_iwjr92_k$()[this.m5__1] = this.get_xi_kntnk6_k$()[this.n1__1] - this.get_xi_kntnk6_k$()[this.n5__1];
        this.get_outXr_iwjr9b_k$()[this.m6__1] = this.get_xr_kntnjx_k$()[this.n3__1] + this.get_xr_kntnjx_k$()[this.n7__1];
        this.get_outXi_iwjr92_k$()[this.m6__1] = this.get_xi_kntnk6_k$()[this.n3__1] + this.get_xi_kntnk6_k$()[this.n7__1];
        this.get_outXr_iwjr9b_k$()[this.m7__1] = this.get_xr_kntnjx_k$()[this.n3__1] - this.get_xr_kntnjx_k$()[this.n7__1];
        this.get_outXi_iwjr92_k$()[this.m7__1] = this.get_xi_kntnk6_k$()[this.n3__1] - this.get_xi_kntnk6_k$()[this.n7__1];
        Rr = this.get_outXr_iwjr9b_k$()[this.m4__1] + this.get_outXr_iwjr9b_k$()[this.m6__1];
        Ri = this.get_outXi_iwjr92_k$()[this.m4__1] + this.get_outXi_iwjr92_k$()[this.m6__1];
        Sr = this.get_outXi_iwjr92_k$()[this.m6__1] - this.get_outXi_iwjr92_k$()[this.m4__1];
        Si = this.get_outXr_iwjr9b_k$()[this.m4__1] - this.get_outXr_iwjr9b_k$()[this.m6__1];
        this.get_outXr_iwjr9b_k$()[this.m4__1] = this.get_outXr_iwjr9b_k$()[this.m0__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m4__1] = this.get_outXi_iwjr92_k$()[this.m0__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m6__1] = this.get_outXr_iwjr9b_k$()[this.m2__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m6__1] = this.get_outXi_iwjr92_k$()[this.m2__1] + Si;
        var tmp8_array = this.get_outXr_iwjr9b_k$();
        var tmp9_index0 = this.m0__1;
        tmp8_array[tmp9_index0] = tmp8_array[tmp9_index0] + Rr;
        var tmp10_array = this.get_outXi_iwjr92_k$();
        var tmp11_index0 = this.m0__1;
        tmp10_array[tmp11_index0] = tmp10_array[tmp11_index0] + Ri;
        var tmp12_array = this.get_outXr_iwjr9b_k$();
        var tmp13_index0 = this.m2__1;
        tmp12_array[tmp13_index0] = tmp12_array[tmp13_index0] - Sr;
        var tmp14_array = this.get_outXi_iwjr92_k$();
        var tmp15_index0 = this.m2__1;
        tmp14_array[tmp15_index0] = tmp14_array[tmp15_index0] - Si;
        T1r = Companion_getInstance_3().SQRT2BY2__1 * (this.get_outXr_iwjr9b_k$()[this.m5__1] + this.get_outXi_iwjr92_k$()[this.m5__1]);
        T1i = Companion_getInstance_3().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[this.m5__1] - this.get_outXr_iwjr9b_k$()[this.m5__1]);
        T3r = Companion_getInstance_3().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[this.m7__1] - this.get_outXr_iwjr9b_k$()[this.m7__1]);
        T3i = -Companion_getInstance_3().SQRT2BY2__1 * (this.get_outXi_iwjr92_k$()[this.m7__1] + this.get_outXr_iwjr9b_k$()[this.m7__1]);
        Rr = T1r + T3r;
        Ri = T1i + T3i;
        Sr = T3i - T1i;
        Si = T1r - T3r;
        this.get_outXr_iwjr9b_k$()[this.m5__1] = this.get_outXr_iwjr9b_k$()[this.m1__1] - Rr;
        this.get_outXi_iwjr92_k$()[this.m5__1] = this.get_outXi_iwjr92_k$()[this.m1__1] - Ri;
        this.get_outXr_iwjr9b_k$()[this.m7__1] = this.get_outXr_iwjr9b_k$()[this.m3__1] + Sr;
        this.get_outXi_iwjr92_k$()[this.m7__1] = this.get_outXi_iwjr92_k$()[this.m3__1] + Si;
        var tmp16_array = this.get_outXr_iwjr9b_k$();
        var tmp17_index0 = this.m1__1;
        tmp16_array[tmp17_index0] = tmp16_array[tmp17_index0] + Rr;
        var tmp18_array = this.get_outXi_iwjr92_k$();
        var tmp19_index0 = this.m1__1;
        tmp18_array[tmp19_index0] = tmp18_array[tmp19_index0] + Ri;
        var tmp20_array = this.get_outXr_iwjr9b_k$();
        var tmp21_index0 = this.m3__1;
        tmp20_array[tmp21_index0] = tmp20_array[tmp21_index0] - Sr;
        var tmp22_array = this.get_outXi_iwjr92_k$();
        var tmp23_index0 = this.m3__1;
        tmp22_array[tmp23_index0] = tmp22_array[tmp23_index0] - Si;
      };
      CDFTsr8.$metadata$ = classMeta("CDFTsr8", void 0, void 0, void 0, void 0, CDFTsr.prototype);
      function _get_N__7mlo03($this) {
        return $this.N_1;
      }
      function _get_N2__ndbhwn($this) {
        return $this.N2__1;
      }
      function _get_N4__ndbhyd($this) {
        return $this.N4__1;
      }
      function _get_xr__ndcekx($this) {
        return $this.xr_1;
      }
      function _get_xi__ndced6($this) {
        return $this.xi_1;
      }
      function _get_Xr__ndbqup($this) {
        return $this.Xr_1;
      }
      function _get_Xi__ndbqmy($this) {
        return $this.Xi_1;
      }
      function _get_dft__e670yn_0($this) {
        return $this.dft_1;
      }
      function _get_c__7mloi6_1($this) {
        return $this.c_1;
      }
      function _get_s__7mlovy_1($this) {
        return $this.s_1;
      }
      function Companion_4() {
        Companion_instance_4 = this;
      }
      Companion_4.prototype.dftProduct = function(kernel, transform2, sign) {
        if (!(kernel.length === transform2.length))
          throw IllegalArgumentException_init_$Create$("kernel and transform arrays must have the same size");
        var n2 = kernel.length;
        var half = n2 / 2 | 0;
        var tmp0_array = transform2;
        var tmp1_index0 = 0;
        tmp0_array[tmp1_index0] = tmp0_array[tmp1_index0] * kernel[0];
        var tmp2_array = transform2;
        var tmp3_index0 = half;
        tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] * kernel[half];
        var tmp;
        var inductionVariable = 1;
        var last = half - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var im = n2 - i | 0;
            tmp = kernel[i] * transform2[i] - sign * kernel[im] * transform2[im];
            transform2[im] = kernel[i] * transform2[im] + sign * kernel[im] * transform2[i];
            transform2[i] = tmp;
          } while (!(i === last));
      };
      Companion_4.$metadata$ = objectMeta("Companion");
      var Companion_instance_4;
      function Companion_getInstance_4() {
        if (Companion_instance_4 == null)
          new Companion_4();
        return Companion_instance_4;
      }
      function RDFT2(log2N) {
        Companion_getInstance_4();
        if (log2N < 4)
          throw IllegalArgumentException_init_$Create$("DFT size must be >= 16");
        this.N_1 = 1 << log2N;
        this.N2__1 = this.N_1 / 2 | 0;
        this.N4__1 = this.N_1 / 4 | 0;
        this.xr_1 = new Float32Array(this.N2__1);
        this.xi_1 = new Float32Array(this.N2__1);
        this.Xr_1 = new Float32Array(this.N2__1);
        this.Xi_1 = new Float32Array(this.N2__1);
        this.s_1 = new Float32Array(this.N4__1);
        this.c_1 = new Float32Array(this.N4__1);
        var inductionVariable = 0;
        var last = this.N4__1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp$ret$0;
            var tmp0_sin = 2 * get_PI() / this.N_1 * i;
            tmp$ret$0 = Math.sin(tmp0_sin);
            this.s_1[i] = tmp$ret$0;
            var tmp$ret$1;
            var tmp1_cos = 2 * get_PI() / this.N_1 * i;
            tmp$ret$1 = Math.cos(tmp1_cos);
            this.c_1[i] = tmp$ret$1;
          } while (!(i === last));
        this.dft_1 = CDFT_ofLogSize(log2N - 1 | 0);
      }
      RDFT2.prototype.evaluate = function(x2, X) {
        var inductionVariable = 0;
        var last = this.N2__1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var j = i << 1;
            var tmp1 = j;
            j = tmp1 + 1 | 0;
            this.xr_1[i] = x2[tmp1];
            this.xi_1[i] = x2[j];
          } while (!(i === last));
        this.dft_1.evaluateCDFT(this.xr_1, this.xi_1, this.Xr_1, this.Xi_1);
        X[0] = this.Xr_1[0] + this.Xi_1[0];
        X[this.N2__1] = this.Xr_1[0] - this.Xi_1[0];
        var N2pk = this.N2__1 + 1 | 0;
        var N2mk = this.N2__1 - 1 | 0;
        var Nmk = this.N_1 - 1 | 0;
        var inductionVariable_0 = 1;
        var last_0 = this.N4__1 - 1 | 0;
        if (inductionVariable_0 <= last_0)
          do {
            var k = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var Xrk = this.Xr_1[k];
            var Xik = this.Xi_1[k];
            var XrN2mk = this.Xr_1[N2mk];
            var XiN2mk = this.Xi_1[N2mk];
            var Sr = (Xrk + XrN2mk) / 2;
            var Si = (Xik - XiN2mk) / 2;
            var Dr = (Xik + XiN2mk) / 2;
            var Di = (XrN2mk - Xrk) / 2;
            var tmp = this.c_1[k] * Dr + this.s_1[k] * Di;
            Di = this.c_1[k] * Di - this.s_1[k] * Dr;
            Dr = tmp;
            X[k] = Sr + Dr;
            X[Nmk] = Si + Di;
            X[N2mk] = Sr - Dr;
            X[N2pk] = Di - Si;
            var tmp3 = N2pk;
            N2pk = tmp3 + 1 | 0;
            var tmp4 = N2mk;
            N2mk = tmp4 - 1 | 0;
            var tmp5 = Nmk;
            Nmk = tmp5 - 1 | 0;
          } while (!(k === last_0));
        X[this.N4__1] = this.Xr_1[this.N4__1];
        X[this.N2__1 + this.N4__1 | 0] = -this.Xi_1[this.N4__1];
      };
      RDFT2.prototype.evaluateInverse = function(X, x2) {
        this.Xr_1[0] = X[0] + X[this.N2__1];
        this.Xi_1[0] = X[0] - X[this.N2__1];
        var N2pk = this.N2__1 + 1 | 0;
        var N2mk = this.N2__1 - 1 | 0;
        var Nmk = this.N_1 - 1 | 0;
        var inductionVariable = 1;
        var last = this.N4__1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var k = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var Xrk = X[k];
            var Xik = X[Nmk];
            var XrkpN2 = X[N2mk];
            var XikpN2 = -X[N2pk];
            var Dr = Xrk - XrkpN2;
            var Di = Xik - XikpN2;
            this.Xr_1[k] = Xrk + XrkpN2 - this.s_1[k] * Dr - this.c_1[k] * Di;
            this.Xi_1[k] = Xik + XikpN2 + this.c_1[k] * Dr - this.s_1[k] * Di;
            var tmp1 = N2pk;
            N2pk = tmp1 + 1 | 0;
            var tmp2 = N2mk;
            N2mk = tmp2 - 1 | 0;
            var tmp3 = Nmk;
            Nmk = tmp3 - 1 | 0;
          } while (!(k === last));
        this.Xr_1[this.N4__1] = 2 * X[this.N4__1];
        this.Xi_1[this.N4__1] = -2 * X[this.N2__1 + this.N4__1 | 0];
        N2pk = (this.N2__1 + this.N4__1 | 0) + 1 | 0;
        N2mk = this.N4__1 - 1 | 0;
        Nmk = (this.N_1 - this.N4__1 | 0) - 1 | 0;
        var reflect2 = this.N4__1 - 1 | 0;
        var inductionVariable_0 = this.N4__1 + 1 | 0;
        var last_0 = this.N2__1 - 1 | 0;
        if (inductionVariable_0 <= last_0)
          do {
            var k_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var Xrk_0 = X[k_0];
            var Xik_0 = X[Nmk];
            var XrkpN2_0 = X[N2mk];
            var XikpN2_0 = -X[N2pk];
            var Dr_0 = Xrk_0 - XrkpN2_0;
            var Di_0 = Xik_0 - XikpN2_0;
            this.Xr_1[k_0] = Xrk_0 + XrkpN2_0 - this.s_1[reflect2] * Dr_0 + this.c_1[reflect2] * Di_0;
            this.Xi_1[k_0] = Xik_0 + XikpN2_0 - this.c_1[reflect2] * Dr_0 - this.s_1[reflect2] * Di_0;
            var tmp5 = N2pk;
            N2pk = tmp5 + 1 | 0;
            var tmp6 = N2mk;
            N2mk = tmp6 - 1 | 0;
            var tmp7 = Nmk;
            Nmk = tmp7 - 1 | 0;
            var tmp8 = reflect2;
            reflect2 = tmp8 - 1 | 0;
          } while (!(k_0 === last_0));
        this.dft_1.evaluateCDFT(this.Xr_1, this.Xi_1, this.xr_1, this.xi_1);
        x2[0] = this.xr_1[0] / this.N_1;
        x2[1] = this.xi_1[0] / this.N_1;
        var j = this.N2__1 - 1 | 0;
        var inductionVariable_1 = 1;
        var last_1 = this.N2__1 - 1 | 0;
        if (inductionVariable_1 <= last_1)
          do {
            var k_1 = inductionVariable_1;
            inductionVariable_1 = inductionVariable_1 + 1 | 0;
            var i = k_1 << 1;
            var tmp10 = i;
            i = tmp10 + 1 | 0;
            x2[tmp10] = this.xr_1[j] / this.N_1;
            x2[i] = this.xi_1[j] / this.N_1;
            var tmp11 = j;
            j = tmp11 - 1 | 0;
          } while (!(k_1 === last_1));
      };
      RDFT2.$metadata$ = classMeta("RDFT");
      function _get_order__d67t8d($this) {
        return $this.order_1;
      }
      function _get_x__7mlp09($this) {
        return $this.x_1;
      }
      function _get_y__7mlp14($this) {
        return $this.y_1;
      }
      function _get_weights__qpj14m($this) {
        return $this.weights_1;
      }
      function Companion_5() {
        Companion_instance_5 = this;
      }
      Companion_5.prototype.BarycentricWeights = function(z2) {
        var n2 = z2.length;
        var retval = new Float64Array(n2);
        var inductionVariable = 0;
        var last = n2 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var j = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var w = 1;
            var inductionVariable_0 = 0;
            var last_0 = n2 - 1 | 0;
            if (inductionVariable_0 <= last_0)
              do {
                var i = inductionVariable_0;
                inductionVariable_0 = inductionVariable_0 + 1 | 0;
                if (!(i === j))
                  w = w * (z2[j] - z2[i]);
              } while (!(i === last_0));
            retval[j] = 1 / w;
          } while (!(j === last));
        return retval;
      };
      Companion_5.$metadata$ = objectMeta("Companion");
      var Companion_instance_5;
      function Companion_getInstance_5() {
        if (Companion_instance_5 == null)
          new Companion_5();
        return Companion_instance_5;
      }
      function LagrangePolynomial2(x2, y2) {
        Companion_getInstance_5();
        if (!(x2.length === y2.length))
          throw IllegalArgumentException_init_$Create$("Lengths of x and y arrays do not match");
        var tmp = this;
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = x2;
        tmp$ret$1 = tmp$ret$0.slice();
        tmp.x_1 = tmp$ret$1;
        var tmp_0 = this;
        var tmp$ret$3;
        var tmp$ret$2;
        tmp$ret$2 = y2;
        tmp$ret$3 = tmp$ret$2.slice();
        tmp_0.y_1 = tmp$ret$3;
        this.order_1 = x2.length - 1 | 0;
        this.weights_1 = Companion_getInstance_5().BarycentricWeights(x2);
      }
      LagrangePolynomial2.prototype.order = function() {
        return this.order_1;
      };
      LagrangePolynomial2.prototype.evaluateAt = function(xp) {
        var num = 0;
        var denom = 0;
        var inductionVariable = 0;
        var last = this.order_1;
        if (inductionVariable <= last)
          $l$loop: do {
            var j = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            if (xp === this.x_1[j]) {
              num = this.y_1[j];
              denom = 1;
              break $l$loop;
            }
            var term = this.weights_1[j] / (xp - this.x_1[j]);
            num = num + term * this.y_1[j];
            denom = denom + term;
          } while (!(j === last));
        return num / denom;
      };
      LagrangePolynomial2.prototype.ChebyshevNodes = function(a, b, n2) {
        var t02 = (a + b) / 2;
        var t12 = (b - 1) / 2;
        var retval = new Float64Array(n2);
        var inductionVariable = 0;
        var last = n2 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp$ret$0;
            var tmp0_cos = ((imul(2, i) + 1 | 0) / imul(2, n2) | 0) * get_PI();
            tmp$ret$0 = Math.cos(tmp0_cos);
            retval[i] = t02 + t12 * tmp$ret$0;
          } while (!(i === last));
        return retval;
      };
      LagrangePolynomial2.$metadata$ = classMeta("LagrangePolynomial");
      function Polynomial_init_$Init$(a, $this) {
        Polynomial2.call($this);
        $this._order_1 = a.length - 1 | 0;
        var tmp = $this;
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = a;
        tmp$ret$1 = tmp$ret$0.slice();
        tmp.a_1 = tmp$ret$1;
        return $this;
      }
      function Polynomial_ofArray(a) {
        return Polynomial_init_$Init$(a, Object.create(Polynomial2.prototype));
      }
      function Polynomial_init_$Init$_0(B, $this) {
        Polynomial2.call($this);
        $this._order_1 = B._order_1;
        var tmp = $this;
        var tmp$ret$1;
        var tmp0_copyOf = B.a_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_copyOf;
        tmp$ret$1 = tmp$ret$0.slice();
        tmp.a_1 = tmp$ret$1;
        return $this;
      }
      function Polynomial_ofPolynomial(B) {
        return Polynomial_init_$Init$_0(B, Object.create(Polynomial2.prototype));
      }
      function Polynomial_init_$Init$_1(order, $this) {
        Polynomial2.call($this);
        $this._order_1 = order;
        $this.a_1 = new Float64Array(order + 1 | 0);
        return $this;
      }
      function Polynomial_ofDegree(order) {
        return Polynomial_init_$Init$_1(order, Object.create(Polynomial2.prototype));
      }
      function Polynomial_init_$Init$_2(c, $this) {
        Polynomial2.call($this);
        $this._order_1 = 0;
        $this.a_1 = new Float64Array(1);
        $this.a_1[0] = c;
        return $this;
      }
      function Polynomial_ofConstant(c) {
        return Polynomial_init_$Init$_2(c, Object.create(Polynomial2.prototype));
      }
      Polynomial2.prototype.set_a_suc4n9_k$ = function(_set____db54di) {
        this.a_1 = _set____db54di;
      };
      Polynomial2.prototype.get_a_1mhr5k_k$ = function() {
        return this.a_1;
      };
      Polynomial2.prototype.set__order_ax9ysk_k$ = function(_set____db54di) {
        this._order_1 = _set____db54di;
      };
      Polynomial2.prototype.get__order_a42a1k_k$ = function() {
        return this._order_1;
      };
      Polynomial2.prototype.trim = function() {
        var i = this._order_1;
        var n2 = 0;
        while (this.a_1[i] === 0) {
          var tmp0 = n2;
          n2 = tmp0 + 1 | 0;
          var tmp1 = i;
          i = tmp1 - 1 | 0;
        }
        if (n2 > 0) {
          var b = new Float64Array((this._order_1 + 1 | 0) - n2 | 0);
          var inductionVariable = 0;
          var last = b.length - 1 | 0;
          if (inductionVariable <= last)
            do {
              var j = inductionVariable;
              inductionVariable = inductionVariable + 1 | 0;
              b[j] = this.a_1[j];
            } while (inductionVariable <= last);
          this.a_1 = b;
          var tmp3_this = this;
          tmp3_this._order_1 = tmp3_this._order_1 - n2 | 0;
        }
      };
      Polynomial2.prototype.order = function() {
        return this._order_1;
      };
      Polynomial2.prototype.coefficients = function() {
        var tmp$ret$1;
        var tmp0_copyOf = this.a_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_copyOf;
        tmp$ret$1 = tmp$ret$0.slice();
        return tmp$ret$1;
      };
      Polynomial2.prototype.plusReal = function(c) {
        var retval = Polynomial_ofDegree(this._order_1);
        var tmp = retval;
        var tmp$ret$1;
        var tmp0_copyOf = this.a_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_copyOf;
        tmp$ret$1 = tmp$ret$0.slice();
        tmp.a_1 = tmp$ret$1;
        var tmp0_array = retval.a_1;
        var tmp1_index0 = 0;
        tmp0_array[tmp1_index0] = tmp0_array[tmp1_index0] + c;
        return retval;
      };
      Polynomial2.prototype.plusEqualsReal = function(c) {
        var tmp0_array = this.a_1;
        var tmp1_index0 = 0;
        tmp0_array[tmp1_index0] = tmp0_array[tmp1_index0] + c;
      };
      Polynomial2.prototype.plusPolynomial = function(B) {
        var tmp$ret$0;
        var tmp0_max = this._order_1;
        var tmp1_max = B._order_1;
        tmp$ret$0 = Math.max(tmp0_max, tmp1_max);
        var retval = Polynomial_ofDegree(tmp$ret$0);
        var inductionVariable = 0;
        var last = this._order_1;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            retval.a_1[i] = this.a_1[i];
          } while (!(i === last));
        var inductionVariable_0 = 0;
        var last_0 = B._order_1;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var tmp2_array = retval.a_1;
            var tmp3_index0 = i_0;
            tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] + B.a_1[i_0];
          } while (!(i_0 === last_0));
        return retval;
      };
      Polynomial2.prototype.plusEqualsPolynomial = function(B) {
        var tmp$ret$0;
        var tmp0_max = this._order_1;
        var tmp1_max = B._order_1;
        tmp$ret$0 = Math.max(tmp0_max, tmp1_max);
        var A = new Float64Array(tmp$ret$0);
        var inductionVariable = 0;
        var last = this._order_1;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            A[i] = this.a_1[i];
          } while (!(i === last));
        var inductionVariable_0 = 0;
        var last_0 = B._order_1;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var tmp2_array = A;
            var tmp3_index0 = i_0;
            tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] + B.a_1[i_0];
          } while (!(i_0 === last_0));
        this.a_1 = A;
        this._order_1 = A.length - 1 | 0;
      };
      Polynomial2.prototype.minusReal = function(c) {
        return this.plusReal(-c);
      };
      Polynomial2.prototype.minusEqualsReal = function(c) {
        this.plusEqualsReal(-c);
      };
      Polynomial2.prototype.minusPolynomial = function(B) {
        var tmp$ret$0;
        var tmp0_max = this._order_1;
        var tmp1_max = B._order_1;
        tmp$ret$0 = Math.max(tmp0_max, tmp1_max);
        var retval = Polynomial_ofDegree(tmp$ret$0);
        var inductionVariable = 0;
        var last = this._order_1;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            retval.a_1[i] = this.a_1[i];
          } while (!(i === last));
        var inductionVariable_0 = 0;
        var last_0 = B._order_1;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var tmp2_array = retval.a_1;
            var tmp3_index0 = i_0;
            tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] - B.a_1[i_0];
          } while (!(i_0 === last_0));
        return retval;
      };
      Polynomial2.prototype.minusEqualsPolynomial = function(B) {
        var tmp$ret$0;
        var tmp0_max = this._order_1;
        var tmp1_max = B._order_1;
        tmp$ret$0 = Math.max(tmp0_max, tmp1_max);
        var A = new Float64Array(tmp$ret$0);
        var inductionVariable = 0;
        var last = this._order_1;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            A[i] = this.a_1[i];
          } while (!(i === last));
        var inductionVariable_0 = 0;
        var last_0 = B._order_1;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var tmp2_array = A;
            var tmp3_index0 = i_0;
            tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] - B.a_1[i_0];
          } while (!(i_0 === last_0));
        this.a_1 = A;
        this._order_1 = A.length - 1 | 0;
      };
      Polynomial2.prototype.timesReal = function(c) {
        var retval = Polynomial_ofDegree(this._order_1);
        var inductionVariable = 0;
        var last = this._order_1;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            retval.a_1[i] = c * this.a_1[i];
          } while (!(i === last));
        return retval;
      };
      Polynomial2.prototype.timesEqualsReal = function(c) {
        var inductionVariable = 0;
        var last = this._order_1;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp1_array = this.a_1;
            var tmp2_index0 = i;
            tmp1_array[tmp2_index0] = tmp1_array[tmp2_index0] * c;
          } while (!(i === last));
      };
      Polynomial2.prototype.timesPolynomial = function(B) {
        var b = B.a_1;
        var prod = new Float64Array((this._order_1 + B._order_1 | 0) + 1 | 0);
        var inductionVariable = 0;
        var last = B._order_1;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var inductionVariable_0 = 0;
            var last_0 = this._order_1;
            if (inductionVariable_0 <= last_0)
              do {
                var j = inductionVariable_0;
                inductionVariable_0 = inductionVariable_0 + 1 | 0;
                var tmp2_array = prod;
                var tmp3_index0 = i + j | 0;
                tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] + b[i] * this.a_1[j];
              } while (!(j === last_0));
          } while (!(i === last));
        return Polynomial_ofArray(prod);
      };
      Polynomial2.prototype.timesEqualsPolynomial = function(B) {
        var b = B.a_1;
        var prod = new Float64Array((this._order_1 + B._order_1 | 0) + 1 | 0);
        var inductionVariable = 0;
        var last = B._order_1;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var inductionVariable_0 = 0;
            var last_0 = this._order_1;
            if (inductionVariable_0 <= last_0)
              do {
                var j = inductionVariable_0;
                inductionVariable_0 = inductionVariable_0 + 1 | 0;
                var tmp2_array = prod;
                var tmp3_index0 = i + j | 0;
                tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] + b[i] * this.a_1[j];
              } while (!(j === last_0));
          } while (!(i === last));
        this.a_1 = prod;
        var tmp4_this = this;
        tmp4_this._order_1 = tmp4_this._order_1 + B._order_1 | 0;
      };
      Polynomial2.prototype.overReal = function(c) {
        var tmp = new Float64Array(this._order_1 + 1 | 0);
        var inductionVariable = 0;
        var last = (this._order_1 + 1 | 0) - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            tmp[i] = this.a_1[i] / c;
          } while (!(i === last));
        return Polynomial_ofArray(tmp);
      };
      Polynomial2.prototype.overEqualsReal = function(c) {
        var inductionVariable = 0;
        var last = (this._order_1 + 1 | 0) - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp1_array = this.a_1;
            var tmp2_index0 = i;
            tmp1_array[tmp2_index0] = tmp1_array[tmp2_index0] / c;
          } while (!(i === last));
      };
      Polynomial2.prototype.overEqualsPolynomial = function(B) {
        return Rational_ofPolynomials(this, B);
      };
      Polynomial2.prototype.derivative = function() {
        var tmp = new Float64Array(this._order_1);
        var inductionVariable = 0;
        var last = this._order_1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            tmp[i] = (i + 1 | 0) * this.a_1[i + 1 | 0];
          } while (!(i === last));
        return Polynomial_ofArray(tmp);
      };
      Polynomial2.prototype.evaluateReal = function(x2) {
        var retval = this.a_1[this._order_1];
        var inductionVariable = this._order_1 - 1 | 0;
        if (0 <= inductionVariable)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + -1 | 0;
            retval = x2 * retval + this.a_1[i];
          } while (0 <= inductionVariable);
        return retval;
      };
      Polynomial2.prototype.evaluateComplex = function(c) {
        var retval = Complex_fromReal(this.a_1[this._order_1]);
        var inductionVariable = this._order_1 - 1 | 0;
        if (0 <= inductionVariable)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + -1 | 0;
            retval = retval.timesComplex(c).plusReal(this.a_1[i]);
          } while (0 <= inductionVariable);
        return retval;
      };
      Polynomial2.prototype.groupDelay = function(omega) {
        if (this._order_1 === 0)
          return 0;
        else {
          var c = new Complex2(0, omega);
          var N = this.derivative().evaluateComplex(c);
          var D = this.evaluateComplex(c);
          return -N.overComplex(D).real();
        }
      };
      Polynomial2.prototype.discreteTimeGroupDelay = function(Omega) {
        var c = Companion_getInstance_8().exp(new Complex2(0, -Omega));
        var N = Complex_fromReal(this.a_1[this._order_1] * this._order_1);
        var inductionVariable = this._order_1 - 1 | 0;
        if (0 <= inductionVariable)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + -1 | 0;
            N = N.timesComplex(c).plusReal(this.a_1[i] * i);
          } while (0 <= inductionVariable);
        var D = this.evaluateComplex(c);
        return N.overComplex(D).real();
      };
      Polynomial2.prototype.reflectionCoefficients = function() {
        var k = new Float64Array(this._order_1);
        var b = new Float64Array(this._order_1 + 1 | 0);
        b[0] = 1;
        var inductionVariable = 0;
        var last = this._order_1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            b[i + 1 | 0] = this.a_1[i + 1 | 0] / this.a_1[0];
          } while (!(i === last));
        var inductionVariable_0 = this._order_1;
        if (1 <= inductionVariable_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + -1 | 0;
            k[i_0 - 1 | 0] = b[i_0];
            var scale = 1 - k[i_0 - 1 | 0] * k[i_0 - 1 | 0];
            var c = new Float64Array(this._order_1);
            var inductionVariable_1 = 0;
            var last_0 = i_0 - 1 | 0;
            if (inductionVariable_1 <= last_0)
              do {
                var j = inductionVariable_1;
                inductionVariable_1 = inductionVariable_1 + 1 | 0;
                c[j] = (b[j] - k[i_0 - 1 | 0] * b[i_0 - j | 0]) / scale;
              } while (!(j === last_0));
            var inductionVariable_2 = 0;
            var last_1 = i_0 - 1 | 0;
            if (inductionVariable_2 <= last_1)
              do {
                var j_0 = inductionVariable_2;
                inductionVariable_2 = inductionVariable_2 + 1 | 0;
                b[j_0] = c[j_0];
              } while (!(j_0 === last_1));
          } while (1 <= inductionVariable_0);
        return k;
      };
      Polynomial2.prototype.toString = function() {
        var s2 = "";
        var inductionVariable = 0;
        var last = this._order_1;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            if (i >= 0 ? i < 10 : false)
              s2 = s2 + (i.toString() + "    " + this.a_1[i] + new Char(_Char___init__impl__6a9atx(10)));
            else if (i >= 10 ? i <= 100 : false)
              s2 = s2 + (i.toString() + "   " + this.a_1[i] + new Char(_Char___init__impl__6a9atx(10)));
          } while (!(i === last));
        return s2;
      };
      function Polynomial2() {
        this._order_1 = 0;
      }
      Polynomial2.$metadata$ = classMeta("Polynomial");
      Object.defineProperty(Polynomial2.prototype, "a", {
        configurable: true,
        get: Polynomial2.prototype.get_a_1mhr5k_k$,
        set: Polynomial2.prototype.set_a_suc4n9_k$
      });
      Object.defineProperty(Polynomial2.prototype, "_order", {
        configurable: true,
        get: Polynomial2.prototype.get__order_a42a1k_k$,
        set: Polynomial2.prototype.set__order_ax9ysk_k$
      });
      function _get_N__7mlo03_0($this) {
        return $this.N_1;
      }
      function _get_D__7mlnrh($this) {
        return $this.D_1;
      }
      function Rational_init_$Init$(num, denom, $this) {
        Rational2.call($this);
        $this.N_1 = Polynomial_ofArray(num);
        $this.D_1 = Polynomial_ofArray(denom);
        return $this;
      }
      function Rational_ofArrays(num, denom) {
        return Rational_init_$Init$(num, denom, Object.create(Rational2.prototype));
      }
      function Rational_init_$Init$_0(N, D, $this) {
        Rational2.call($this);
        $this.N_1 = Polynomial_ofPolynomial(N);
        $this.D_1 = Polynomial_ofPolynomial(D);
        return $this;
      }
      function Rational_ofPolynomials(N, D) {
        return Rational_init_$Init$_0(N, D, Object.create(Rational2.prototype));
      }
      function Rational_init_$Init$_1(R, $this) {
        Rational2.call($this);
        $this.N_1 = Polynomial_ofPolynomial(R.N_1);
        $this.D_1 = Polynomial_ofPolynomial(R.D_1);
        return $this;
      }
      function Rational_ofRational(R) {
        return Rational_init_$Init$_1(R, Object.create(Rational2.prototype));
      }
      function Rational_init_$Init$_2(c, $this) {
        Rational2.call($this);
        $this.N_1 = Polynomial_ofConstant(c);
        $this.D_1 = Polynomial_ofConstant(1);
        return $this;
      }
      function Rational_ofConstant(c) {
        return Rational_init_$Init$_2(c, Object.create(Rational2.prototype));
      }
      Rational2.prototype.order = function() {
        var tmp$ret$0;
        var tmp0_intArrayOf = new Int32Array([this.N_1.order(), this.D_1.order()]);
        tmp$ret$0 = tmp0_intArrayOf;
        var retval = tmp$ret$0;
        return retval;
      };
      Rational2.prototype.numerator = function() {
        return Polynomial_ofPolynomial(this.N_1);
      };
      Rational2.prototype.denominator = function() {
        return Polynomial_ofPolynomial(this.D_1);
      };
      Rational2.prototype.canonicalForm = function() {
        var scaleN = this.N_1.a_1[this.N_1._order_1];
        var inductionVariable = 0;
        var last = this.N_1.a_1.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp1_array = this.N_1.a_1;
            var tmp2_index0 = i;
            tmp1_array[tmp2_index0] = tmp1_array[tmp2_index0] / scaleN;
          } while (inductionVariable <= last);
        var scaleD = this.D_1.a_1[this.D_1._order_1];
        var inductionVariable_0 = 0;
        var last_0 = this.D_1.a_1.length - 1 | 0;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var tmp4_array = this.D_1.a_1;
            var tmp5_index0 = i_0;
            tmp4_array[tmp5_index0] = tmp4_array[tmp5_index0] / scaleD;
          } while (inductionVariable_0 <= last_0);
        return scaleN / scaleD;
      };
      Rational2.prototype.timesEqualsReal = function(A) {
        this.N_1.timesEqualsReal(A);
      };
      Rational2.prototype.timesEqualsPolynomial = function(P) {
        this.N_1.timesEqualsPolynomial(P);
      };
      Rational2.prototype.timesEqualsRational = function(R) {
        this.N_1.timesEqualsPolynomial(R.N_1);
        this.D_1.timesEqualsPolynomial(R.D_1);
      };
      Rational2.prototype.evaluateReal = function(x2) {
        var retval = 0;
        var num = this.N_1.evaluateReal(x2);
        var denom = this.D_1.evaluateReal(x2);
        if (!(denom === 0))
          retval = num / denom;
        return retval;
      };
      Rational2.prototype.evaluateComplex = function(c) {
        var retval = new Complex2(0, 0);
        var num = this.N_1.evaluateComplex(c);
        var denom = this.D_1.evaluateComplex(c);
        if (!(denom.abs() === 0))
          retval = num.overComplex(denom);
        return retval;
      };
      Rational2.prototype.mapRational = function(S) {
        var P = Polynomial_ofConstant(this.N_1.a_1[this.N_1._order_1]);
        var T = Polynomial_ofConstant(1);
        var inductionVariable = this.N_1._order_1 - 1 | 0;
        if (0 <= inductionVariable)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + -1 | 0;
            T = T.timesPolynomial(S.D_1);
            P = P.timesPolynomial(S.N_1).plusPolynomial(T.timesReal(this.N_1.a_1[i]));
          } while (0 <= inductionVariable);
        var Q = Polynomial_ofConstant(this.D_1.a_1[this.D_1._order_1]);
        T = Polynomial_ofConstant(1);
        var inductionVariable_0 = this.D_1._order_1 - 1 | 0;
        if (0 <= inductionVariable_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + -1 | 0;
            T = T.timesPolynomial(S.D_1);
            Q = Q.timesPolynomial(S.N_1).plusPolynomial(T.timesReal(this.D_1.a_1[i_0]));
          } while (0 <= inductionVariable_0);
        if (this.D_1._order_1 > this.N_1._order_1) {
          var inductionVariable_1 = 0;
          var last = (this.D_1._order_1 - this.N_1._order_1 | 0) - 1 | 0;
          if (inductionVariable_1 <= last)
            do {
              var i_1 = inductionVariable_1;
              inductionVariable_1 = inductionVariable_1 + 1 | 0;
              P = P.timesPolynomial(S.D_1);
            } while (!(i_1 === last));
        } else if (this.N_1._order_1 > this.D_1._order_1) {
          var inductionVariable_2 = 0;
          var last_0 = (this.N_1._order_1 - this.D_1._order_1 | 0) - 1 | 0;
          if (inductionVariable_2 <= last_0)
            do {
              var i_2 = inductionVariable_2;
              inductionVariable_2 = inductionVariable_2 + 1 | 0;
              Q = Q.timesPolynomial(S.D_1);
            } while (!(i_2 === last_0));
        }
        P.trim();
        Q.trim();
        return Rational_ofPolynomials(P, Q);
      };
      Rational2.prototype.residueForReal = function(pole) {
        return this.N_1.evaluateReal(pole) / this.D_1.derivative().evaluateReal(pole);
      };
      Rational2.prototype.residueForComplex = function(pole) {
        return this.N_1.evaluateComplex(pole).overComplex(this.D_1.derivative().evaluateComplex(pole));
      };
      Rational2.prototype.groupDelay = function(omega) {
        return this.N_1.groupDelay(omega) - this.D_1.groupDelay(omega);
      };
      Rational2.prototype.discreteTimeGroupDelay = function(Omega) {
        return this.N_1.discreteTimeGroupDelay(Omega) - this.D_1.discreteTimeGroupDelay(Omega);
      };
      Rational2.prototype.toString = function() {
        return "Numerator: " + this.N_1 + "\n" + ("Denominator: " + this.D_1 + "\n");
      };
      function Rational2() {
      }
      Rational2.$metadata$ = classMeta("Rational");
      function ComplexAnalyticSignal2(realSignal) {
        var tmp = this;
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = realSignal;
        tmp$ret$1 = tmp$ret$0.slice();
        tmp._realPart_1 = tmp$ret$1;
        var transformer2 = new CenteredHilbertTransform2(50, 0.03, 0.97);
        var tmp_0 = transformer2.filter(this._realPart_1);
        Companion_getInstance().zeroShiftArray(tmp_0, -50);
        this._imagPart_1 = new Float32Array(this._realPart_1.length);
        var inductionVariable = 0;
        var last = this._realPart_1.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            this._imagPart_1[i] = tmp_0[i];
          } while (inductionVariable <= last);
      }
      ComplexAnalyticSignal2.prototype.set__realPart_f7bi4z_k$ = function(_set____db54di) {
        this._realPart_1 = _set____db54di;
      };
      ComplexAnalyticSignal2.prototype.get__realPart_47rtll_k$ = function() {
        return this._realPart_1;
      };
      ComplexAnalyticSignal2.prototype.set__imagPart_dn087_k$ = function(_set____db54di) {
        this._imagPart_1 = _set____db54di;
      };
      ComplexAnalyticSignal2.prototype.get__imagPart_47qodp_k$ = function() {
        return this._imagPart_1;
      };
      ComplexAnalyticSignal2.prototype.get_envelope_5cdspl_k$ = function() {
        var retval = new Float32Array(this._realPart_1.length);
        var inductionVariable = 0;
        var last = this._realPart_1.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp$ret$0;
            var tmp0_sqrt = this._realPart_1[i] * this._realPart_1[i] + this._imagPart_1[i] * this._imagPart_1[i];
            tmp$ret$0 = Math.sqrt(tmp0_sqrt);
            retval[i] = tmp$ret$0;
          } while (inductionVariable <= last);
        return retval;
      };
      ComplexAnalyticSignal2.prototype.getRealPart = function() {
        var tmp$ret$1;
        var tmp0_copyOf = this._realPart_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_copyOf;
        tmp$ret$1 = tmp$ret$0.slice();
        return tmp$ret$1;
      };
      ComplexAnalyticSignal2.prototype.getImagPart = function() {
        var tmp$ret$1;
        var tmp0_copyOf = this._imagPart_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_copyOf;
        tmp$ret$1 = tmp$ret$0.slice();
        return tmp$ret$1;
      };
      ComplexAnalyticSignal2.$metadata$ = classMeta("ComplexAnalyticSignal");
      Object.defineProperty(ComplexAnalyticSignal2.prototype, "envelope", {
        configurable: true,
        get: ComplexAnalyticSignal2.prototype.get_envelope_5cdspl_k$
      });
      function _get_rate__dczgbv($this) {
        return $this.rate_1;
      }
      function _get_overlapAdd__wylgj5($this) {
        return $this.overlapAdd_1;
      }
      function _get_buffer__tgqkad($this) {
        return $this.buffer_1;
      }
      function Interpolator2(rate, designFactor, blockSize) {
        this.rate_1 = rate;
        var half = imul(this.rate_1, designFactor);
        var N = imul(2, half) + 1 | 0;
        var kernel = new HammingWindow2(N).array;
        var inductionVariable = 1;
        if (inductionVariable <= half)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp1_array = kernel;
            var tmp2_index0 = half + i | 0;
            var tmp = tmp1_array[tmp2_index0];
            var tmp$ret$0;
            var tmp0_sin = get_PI() * i / this.rate_1;
            tmp$ret$0 = Math.sin(tmp0_sin);
            tmp1_array[tmp2_index0] = tmp * (tmp$ret$0 / (get_PI() * i / this.rate_1));
            kernel[half - i | 0] = kernel[half + i | 0];
          } while (!(i === half));
        this.overlapAdd_1 = OverlapAdd_ofArray(kernel, imul(blockSize, this.rate_1));
        this.buffer_1 = new Float32Array(imul(blockSize, this.rate_1));
      }
      Interpolator2.prototype.interpolate = function(block, interpolatedBlock) {
        Companion_getInstance().stretchArray(block, this.rate_1, this.buffer_1);
        this.overlapAdd_1.filter(this.buffer_1, 0, interpolatedBlock, 0);
      };
      Interpolator2.$metadata$ = classMeta("Interpolator");
      function _set_shiftRegister__p2sj34($this, _set____db54di) {
        $this.shiftRegister_1 = _set____db54di;
      }
      function _get_shiftRegister__9v10ks($this) {
        return $this.shiftRegister_1;
      }
      function _set_fft__4w5psh($this, _set____db54di) {
        $this.fft_1 = _set____db54di;
      }
      function _get_fft__e68axp($this) {
        return $this.fft_1;
      }
      function _set_nfft__9r379t($this, _set____db54di) {
        $this.nfft_1 = _set____db54di;
      }
      function _get_nfft__dav6v9($this) {
        return $this.nfft_1;
      }
      function _set_kernel__mr01oa($this, _set____db54di) {
        $this.kernel_1 = _set____db54di;
      }
      function _get_kernel__o7qmb2($this) {
        return $this.kernel_1;
      }
      function _set_kernelLength__v96yb8($this, _set____db54di) {
        $this.kernelLength_1 = _set____db54di;
      }
      function _get_kernelLength__o86d3s($this) {
        return $this.kernelLength_1;
      }
      function _set_blockSize__tu9q5l($this, _set____db54di) {
        $this.blockSize_1 = _set____db54di;
      }
      function _get_blockSize__jf9r1($this) {
        return $this.blockSize_1;
      }
      function _set_segment__77iylu($this, _set____db54di) {
        $this.segment_1 = _set____db54di;
      }
      function _get_segment__iepbr6($this) {
        return $this.segment_1;
      }
      function _set_transform__8gln3b($this, _set____db54di) {
        $this.transform_1 = _set____db54di;
      }
      function _get_transform__ku8tb9($this) {
        return $this.transform_1;
      }
      function OverlapAdd_init_$Init$(H, blockSize, $this) {
        OverlapAdd2.call($this);
        $this.kernelLength_1 = H.length;
        $this.blockSize_1 = blockSize;
        var clength = (H.length + blockSize | 0) - 1 | 0;
        var log2nfft = 0;
        $this.nfft_1 = 1;
        while ($this.nfft_1 < clength) {
          var tmp0 = log2nfft;
          log2nfft = tmp0 + 1 | 0;
          var tmp1_this = $this;
          tmp1_this.nfft_1 = imul(tmp1_this.nfft_1, 2);
        }
        $this.fft_1 = new RDFT2(log2nfft);
        $this.shiftRegister_1 = new Float32Array($this.nfft_1);
        $this.kernel_1 = new Float32Array($this.nfft_1);
        $this.segment_1 = new Float32Array($this.nfft_1);
        $this.transform_1 = new Float32Array($this.nfft_1);
        var inductionVariable = 0;
        var last = H.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            ensureNotNull($this.segment_1)[i] = H[i];
          } while (inductionVariable <= last);
        ensureNotNull($this.fft_1).evaluate(ensureNotNull($this.segment_1), ensureNotNull($this.kernel_1));
        return $this;
      }
      function OverlapAdd_ofArray(H, blockSize) {
        return OverlapAdd_init_$Init$(H, blockSize, Object.create(OverlapAdd2.prototype));
      }
      function OverlapAdd_init_$Init$_0(H, master, $this) {
        OverlapAdd2.call($this);
        if (!(H.length === master.kernelLength_1))
          throw IllegalArgumentException_init_$Create$("Slave kernel length inconsistent with master OverlapAdd kernel length");
        $this.kernelLength_1 = H.length;
        $this.blockSize_1 = master.blockSize_1;
        $this.fft_1 = master.fft_1;
        $this.nfft_1 = master.nfft_1;
        $this.shiftRegister_1 = new Float32Array($this.nfft_1);
        $this.kernel_1 = new Float32Array($this.nfft_1);
        $this.segment_1 = new Float32Array($this.nfft_1);
        $this.transform_1 = new Float32Array($this.nfft_1);
        var inductionVariable = 0;
        var last = H.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            ensureNotNull($this.segment_1)[i] = H[i];
          } while (inductionVariable <= last);
        ensureNotNull($this.fft_1).evaluate(ensureNotNull($this.segment_1), ensureNotNull($this.kernel_1));
        return $this;
      }
      function OverlapAdd_ofArrayOverlapAdd(H, master) {
        return OverlapAdd_init_$Init$_0(H, master, Object.create(OverlapAdd2.prototype));
      }
      OverlapAdd2.prototype.filter = function(src, sptr, dst, dptr) {
        if (!(src.length === this.blockSize_1))
          throw IllegalArgumentException_init_$Create$("Data array length not equal to blockSize");
        var inductionVariable = 0;
        var last = ensureNotNull(this.segment_1).length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            ensureNotNull(this.segment_1)[i] = 0;
          } while (inductionVariable <= last);
        var inductionVariable_0 = 0;
        var last_0 = this.blockSize_1;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            ensureNotNull(this.segment_1)[i_0] = src[i_0 + sptr | 0];
          } while (!(i_0 === last_0));
        ensureNotNull(this.fft_1).evaluate(ensureNotNull(this.segment_1), ensureNotNull(this.transform_1));
        Companion_getInstance_4().dftProduct(ensureNotNull(this.kernel_1), ensureNotNull(this.transform_1), 1);
        ensureNotNull(this.fft_1).evaluateInverse(ensureNotNull(this.transform_1), ensureNotNull(this.segment_1));
        var inductionVariable_1 = 0;
        var last_1 = this.nfft_1 - 1 | 0;
        if (inductionVariable_1 <= last_1)
          do {
            var i_1 = inductionVariable_1;
            inductionVariable_1 = inductionVariable_1 + 1 | 0;
            var tmp3_array = this.shiftRegister_1;
            var tmp4_index0 = i_1;
            tmp3_array[tmp4_index0] = tmp3_array[tmp4_index0] + ensureNotNull(this.segment_1)[i_1];
          } while (!(i_1 === last_1));
        var inductionVariable_2 = 0;
        var last_2 = this.blockSize_1;
        if (inductionVariable_2 <= last_2)
          do {
            var i_2 = inductionVariable_2;
            inductionVariable_2 = inductionVariable_2 + 1 | 0;
            dst[i_2 + dptr | 0] = this.shiftRegister_1[i_2];
          } while (!(i_2 === last_2));
        Companion_getInstance().zeroShiftArray(this.shiftRegister_1, -this.blockSize_1 | 0);
      };
      OverlapAdd2.prototype.flush = function(dst, dptr) {
        var inductionVariable = 0;
        var last = this.blockSize_1;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            dst[i + dptr | 0] = this.shiftRegister_1[i];
          } while (!(i === last));
        Companion_getInstance().zeroShiftArray(this.shiftRegister_1, -this.blockSize_1 | 0);
      };
      function OverlapAdd2() {
        this.fft_1 = null;
        this.nfft_1 = 0;
        this.kernel_1 = null;
        this.kernelLength_1 = 0;
        this.blockSize_1 = 0;
        this.segment_1 = null;
        this.transform_1 = null;
      }
      OverlapAdd2.$metadata$ = classMeta("OverlapAdd");
      function _get_delta__ikpko7($this) {
        return $this.delta_1;
      }
      function CenteredDifferentiator2(N, delta, OmegaP) {
        FIRTypeIII2.call(this, 1, N);
        this.delta_1 = delta;
        if (!(0 < OmegaP ? OmegaP < 1 : false))
          throw IllegalArgumentException_init_$Create$("Check 0.0 < OmegaP < 1.0");
        this.bands_1[0][0] = 1 / imul(2, N);
        this.bands_1[0][1] = OmegaP;
        this.generateCoefficients();
      }
      CenteredDifferentiator2.prototype.desiredResponse_yw2r0a_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = -get_PI() * Omega / this.delta_1;
        return retval;
      };
      CenteredDifferentiator2.prototype.desiredResponse = function(Omega) {
        return this.desiredResponse_yw2r0a_k$(Omega);
      };
      CenteredDifferentiator2.prototype.weight_3hkr93_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = 1 / Omega;
        return retval;
      };
      CenteredDifferentiator2.prototype.weight = function(Omega) {
        return this.weight_3hkr93_k$(Omega);
      };
      CenteredDifferentiator2.$metadata$ = classMeta("CenteredDifferentiator", void 0, void 0, void 0, void 0, FIRTypeIII2.prototype);
      function CenteredHilbertTransform2(N, Omega1, Omega2) {
        FIRTypeIII2.call(this, 1, N);
        if (!((0 < Omega1 ? Omega1 < Omega2 : false) ? Omega2 < 1 : false))
          throw IllegalArgumentException_init_$Create$("Check 0.0 < Omega1 < Omega2 < 1.0");
        this.bands_1[0][0] = Omega1;
        this.bands_1[0][1] = Omega2;
        this.generateCoefficients();
      }
      CenteredHilbertTransform2.prototype.desiredResponse_yw2r0a_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = 1;
        return retval;
      };
      CenteredHilbertTransform2.prototype.desiredResponse = function(Omega) {
        return this.desiredResponse_yw2r0a_k$(Omega);
      };
      CenteredHilbertTransform2.prototype.weight_3hkr93_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = 1;
        return retval;
      };
      CenteredHilbertTransform2.prototype.weight = function(Omega) {
        return this.weight_3hkr93_k$(Omega);
      };
      CenteredHilbertTransform2.$metadata$ = classMeta("CenteredHilbertTransform", void 0, void 0, void 0, void 0, FIRTypeIII2.prototype);
      function Companion_6() {
        Companion_instance_6 = this;
        this.GRIDDENSITY_1 = 20;
      }
      Companion_6.prototype.get_GRIDDENSITY_9wle8p_k$ = function() {
        return this.GRIDDENSITY_1;
      };
      Companion_6.$metadata$ = objectMeta("Companion");
      var Companion_instance_6;
      function Companion_getInstance_6() {
        if (Companion_instance_6 == null)
          new Companion_6();
        return Companion_instance_6;
      }
      function DesignGrid() {
        Companion_getInstance_6();
        this.gridSize_1 = 0;
        this.containsZero_1 = false;
        this.containsPi_1 = false;
      }
      DesignGrid.prototype.set_grid_bp7z6u_k$ = function(_set____db54di) {
        this.grid_1 = _set____db54di;
      };
      DesignGrid.prototype.get_grid_womu8f_k$ = function() {
        var tmp = this.grid_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("grid");
        }
      };
      DesignGrid.prototype.set_gridSize_fddnyk_k$ = function(_set____db54di) {
        this.gridSize_1 = _set____db54di;
      };
      DesignGrid.prototype.get_gridSize_qjl6ts_k$ = function() {
        return this.gridSize_1;
      };
      DesignGrid.prototype.set_X_mod0ry_k$ = function(_set____db54di) {
        this.X_1 = _set____db54di;
      };
      DesignGrid.prototype.get_X_1mhr5b_k$ = function() {
        var tmp = this.X_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("X");
        }
      };
      DesignGrid.prototype.set_H_3tm5oe_k$ = function(_set____db54di) {
        this.H_1 = _set____db54di;
      };
      DesignGrid.prototype.get_H_1mhr4v_k$ = function() {
        var tmp = this.H_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("H");
        }
      };
      DesignGrid.prototype.set_W_9ksoj5_k$ = function(_set____db54di) {
        this.W_1 = _set____db54di;
      };
      DesignGrid.prototype.get_W_1mhr5a_k$ = function() {
        var tmp = this.W_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("W");
        }
      };
      DesignGrid.prototype.set_bandEdgeIndices_4o2nof_k$ = function(_set____db54di) {
        this.bandEdgeIndices_1 = _set____db54di;
      };
      DesignGrid.prototype.get_bandEdgeIndices_4mq7kc_k$ = function() {
        var tmp = this.bandEdgeIndices_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("bandEdgeIndices");
        }
      };
      DesignGrid.prototype.set_extremaIndices_kapzx9_k$ = function(_set____db54di) {
        this.extremaIndices_1 = _set____db54di;
      };
      DesignGrid.prototype.get_extremaIndices_8bux3s_k$ = function() {
        var tmp = this.extremaIndices_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("extremaIndices");
        }
      };
      DesignGrid.prototype.set_containsZero_c9ryd7_k$ = function(_set____db54di) {
        this.containsZero_1 = _set____db54di;
      };
      DesignGrid.prototype.get_containsZero_uv6ez4_k$ = function() {
        return this.containsZero_1;
      };
      DesignGrid.prototype.set_containsPi_d8e76c_k$ = function(_set____db54di) {
        this.containsPi_1 = _set____db54di;
      };
      DesignGrid.prototype.get_containsPi_hrrp4v_k$ = function() {
        return this.containsPi_1;
      };
      DesignGrid.prototype.toString = function() {
        var out = "";
        var extremum = 0;
        var bandEdgeCount = 0;
        var inductionVariable = 0;
        var last = this.gridSize_1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var Omega = this.get_grid_womu8f_k$()[i];
            var line = "" + toString(toLong(i)) + "  " + Omega + "  " + this.get_X_1mhr5b_k$()[i] + "  " + this.get_H_1mhr4v_k$()[i] + "  " + this.get_W_1mhr5a_k$()[i];
            if (this.get_bandEdgeIndices_4mq7kc_k$()[bandEdgeCount] === i) {
              line = line + "  band edge";
              var tmp1 = bandEdgeCount;
              bandEdgeCount = tmp1 + 1 | 0;
            }
            if (Omega === this.get_grid_womu8f_k$()[this.get_extremaIndices_8bux3s_k$()[extremum]]) {
              line = line + "  extremum";
              var tmp2 = extremum;
              extremum = tmp2 + 1 | 0;
            }
            out = out + (line + new Char(_Char___init__impl__6a9atx(10)));
          } while (!(i === last));
        return out;
      };
      DesignGrid.$metadata$ = classMeta("DesignGrid");
      function _get_Ws1__e5yy64($this) {
        return $this.Ws1__1;
      }
      function _get_Wp__ndbq2a($this) {
        return $this.Wp_1;
      }
      function _get_Ws2__e5yy6z($this) {
        return $this.Ws2__1;
      }
      function EquirippleBandpass2(N, OmegaS1, Ws1, OmegaP1, OmegaP2, Wp, OmegaS2, Ws2) {
        FIRTypeI2.call(this, 3, N);
        this.Ws1__1 = Ws1;
        this.Wp_1 = Wp;
        this.Ws2__1 = Ws2;
        if (!((((0 < OmegaS1 ? OmegaS1 < OmegaP1 : false) ? OmegaP1 < OmegaP2 : false) ? OmegaP2 < OmegaS2 : false) ? OmegaS2 < 1 : false))
          throw IllegalArgumentException_init_$Create$("Band edge specification error, ensure that 0.0 < OmegaS1 < OmegaP1 < OmegaP2 < OmegaS2 < 1.0");
        this.bands_1[0][0] = 0;
        this.bands_1[0][1] = OmegaS1;
        this.bands_1[1][0] = OmegaP1;
        this.bands_1[1][1] = OmegaP2;
        this.bands_1[2][0] = OmegaS2;
        this.bands_1[2][1] = 1;
        this.generateCoefficients();
      }
      EquirippleBandpass2.prototype.desiredResponse_yw2r0a_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[1][0], Omega) ? this.LTE(Omega, this.bands_1[1][1]) : false)
          retval = 1;
        return retval;
      };
      EquirippleBandpass2.prototype.desiredResponse = function(Omega) {
        return this.desiredResponse_yw2r0a_k$(Omega);
      };
      EquirippleBandpass2.prototype.weight_3hkr93_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = this.Ws1__1;
        else if (this.LTE(this.bands_1[1][0], Omega) ? this.LTE(Omega, this.bands_1[1][1]) : false)
          retval = this.Wp_1;
        else if (this.LTE(this.bands_1[2][0], Omega) ? this.LTE(Omega, this.bands_1[2][1]) : false)
          retval = this.Ws2__1;
        return retval;
      };
      EquirippleBandpass2.prototype.weight = function(Omega) {
        return this.weight_3hkr93_k$(Omega);
      };
      EquirippleBandpass2.$metadata$ = classMeta("EquirippleBandpass", void 0, void 0, void 0, void 0, FIRTypeI2.prototype);
      function _get_MAXITER__g0wxxn($this) {
        return $this.MAXITER_1;
      }
      function EquirippleDesigner() {
        EquirippleDesigner_instance = this;
        this.MAXITER_1 = 25;
      }
      EquirippleDesigner.prototype.remez = function(G) {
        var nextrema = G.get_extremaIndices_8bux3s_k$().length;
        var newExtrema = ArrayList_init_$Create$();
        var E = new Float64Array(G.gridSize_1);
        var GA = new Float64Array(G.gridSize_1);
        var niter = 0;
        $l$loop_1: do {
          var delta = this.computeDelta(G);
          var LP = this.constructInterpolatingPolynomial(G, delta);
          var inductionVariable = 0;
          var last = G.gridSize_1 - 1 | 0;
          if (inductionVariable <= last)
            do {
              var i = inductionVariable;
              inductionVariable = inductionVariable + 1 | 0;
              GA[i] = LP.evaluateAt(G.get_X_1mhr5b_k$()[i]);
              E[i] = GA[i] - G.get_H_1mhr4v_k$()[i];
            } while (!(i === last));
          newExtrema.clear_j9y8zo_k$();
          var change = 0;
          var inductionVariable_0 = 0;
          var last_0 = nextrema - 1 | 0;
          if (inductionVariable_0 <= last_0)
            do {
              var currentExtremum = inductionVariable_0;
              inductionVariable_0 = inductionVariable_0 + 1 | 0;
              var currentGridPt = G.get_extremaIndices_8bux3s_k$()[currentExtremum];
              var s2 = this.sgn(E[currentGridPt]);
              var ptr = currentGridPt + 1 | 0;
              if (ptr < G.gridSize_1) {
                $l$loop: while (this.sgn(E[ptr] - E[ptr - 1 | 0]) === s2) {
                  var tmp2 = ptr;
                  ptr = tmp2 + 1 | 0;
                  if (ptr === G.gridSize_1)
                    break $l$loop;
                }
              }
              var tmp3 = ptr;
              ptr = tmp3 - 1 | 0;
              if (ptr === currentGridPt) {
                ptr = currentGridPt - 1 | 0;
                if (ptr >= 0) {
                  $l$loop_0: while (this.sgn(E[ptr] - E[ptr + 1 | 0]) === s2) {
                    var tmp4 = ptr;
                    ptr = tmp4 - 1 | 0;
                    if (ptr < 0)
                      break $l$loop_0;
                  }
                }
                var tmp5 = ptr;
                ptr = tmp5 + 1 | 0;
              }
              newExtrema.add_1j60pz_k$(ptr);
              if (!(ptr === currentGridPt)) {
                var tmp6 = change;
                change = tmp6 + 1 | 0;
              }
            } while (!(currentExtremum === last_0));
          if (G.containsZero_1 ? G.containsPi_1 : false) {
            var gridPi = G.gridSize_1 - 1 | 0;
            if (newExtrema.contains_2ehdt1_k$(0)) {
              if (!newExtrema.contains_2ehdt1_k$(gridPi)) {
                if (!(this.sgn(E[gridPi]) === this.sgn(E[G.get_extremaIndices_8bux3s_k$()[nextrema - 1 | 0]]))) {
                  var tmp$ret$0;
                  var tmp0_abs = E[gridPi];
                  tmp$ret$0 = Math.abs(tmp0_abs);
                  var tmp = tmp$ret$0;
                  var tmp$ret$1;
                  var tmp1_abs = E[0];
                  tmp$ret$1 = Math.abs(tmp1_abs);
                  if (tmp > tmp$ret$1) {
                    newExtrema.removeAt_qvpkxi_k$(0);
                    newExtrema.add_1j60pz_k$(gridPi);
                    var tmp7 = change;
                    change = tmp7 + 1 | 0;
                  }
                }
              }
            } else {
              if (newExtrema.contains_2ehdt1_k$(gridPi)) {
                if (!(this.sgn(E[0]) === this.sgn(E[G.get_extremaIndices_8bux3s_k$()[0]]))) {
                  var tmp$ret$2;
                  var tmp2_abs = E[0];
                  tmp$ret$2 = Math.abs(tmp2_abs);
                  var tmp_0 = tmp$ret$2;
                  var tmp$ret$3;
                  var tmp3_abs = E[gridPi];
                  tmp$ret$3 = Math.abs(tmp3_abs);
                  if (tmp_0 > tmp$ret$3) {
                    newExtrema.removeAt_qvpkxi_k$(newExtrema.get_size_woubt6_k$() - 1 | 0);
                    newExtrema.add_ydlf05_k$(0, 0);
                    var tmp8 = change;
                    change = tmp8 + 1 | 0;
                  }
                }
              }
            }
          }
          if (change === 0)
            break $l$loop_1;
          var inductionVariable_1 = 0;
          var last_1 = nextrema - 1 | 0;
          if (inductionVariable_1 <= last_1)
            do {
              var i_0 = inductionVariable_1;
              inductionVariable_1 = inductionVariable_1 + 1 | 0;
              G.get_extremaIndices_8bux3s_k$()[i_0] = newExtrema.get_fkrdnv_k$(i_0);
            } while (!(i_0 === last_1));
          var tmp10 = niter;
          niter = tmp10 + 1 | 0;
        } while (niter < this.MAXITER_1);
      };
      EquirippleDesigner.prototype.computeDelta = function(G) {
        var nextrema = G.get_extremaIndices_8bux3s_k$().length;
        var extrema = new Float64Array(nextrema);
        var inductionVariable = 0;
        var last = nextrema - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            extrema[i] = G.get_X_1mhr5b_k$()[G.get_extremaIndices_8bux3s_k$()[i]];
          } while (!(i === last));
        var gamma2 = Companion_getInstance_5().BarycentricWeights(extrema);
        var num = 0;
        var denom = 0;
        var s2 = 1;
        var inductionVariable_0 = 0;
        var last_0 = nextrema - 1 | 0;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var j = G.get_extremaIndices_8bux3s_k$()[i_0];
            num = num + gamma2[i_0] * G.get_H_1mhr4v_k$()[j];
            denom = denom + s2 * gamma2[i_0] / G.get_W_1mhr5a_k$()[j];
            s2 = -s2;
          } while (!(i_0 === last_0));
        return num / denom;
      };
      EquirippleDesigner.prototype.constructInterpolatingPolynomial = function(G, delta) {
        var extremaSubset = new Float64Array(G.get_extremaIndices_8bux3s_k$().length - 1 | 0);
        var n2 = extremaSubset.length;
        var x2 = new Float64Array(n2);
        var f = new Float64Array(n2);
        var s2 = 1;
        var inductionVariable = 0;
        var last = n2 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var j = G.get_extremaIndices_8bux3s_k$()[i];
            x2[i] = G.get_X_1mhr5b_k$()[j];
            f[i] = G.get_H_1mhr4v_k$()[j] - s2 * delta / G.get_W_1mhr5a_k$()[j];
            s2 = -s2;
          } while (!(i === last));
        return new LagrangePolynomial2(x2, f);
      };
      EquirippleDesigner.prototype.calculateCoefficients = function(G, Nc) {
        var LP = this.constructInterpolatingPolynomial(G, this.computeDelta(G));
        var log2nfft = 6;
        var nfft = 64;
        while (nfft < Nc) {
          nfft = imul(nfft, 2);
          var tmp0 = log2nfft;
          log2nfft = tmp0 + 1 | 0;
        }
        var X = new Float32Array(nfft);
        var x2 = new Float32Array(nfft);
        var inductionVariable = 0;
        var last = nfft / 2 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp$ret$0;
            var tmp0_cos = 2 * get_PI() * i / nfft;
            tmp$ret$0 = Math.cos(tmp0_cos);
            X[i] = LP.evaluateAt(tmp$ret$0);
          } while (!(i === last));
        var dft = new RDFT2(log2nfft);
        dft.evaluateInverse(X, x2);
        return x2;
      };
      EquirippleDesigner.prototype.sgn = function(x2) {
        if (x2 > 0)
          return 1;
        else if (x2 < 0)
          return -1;
        else
          return 0;
      };
      EquirippleDesigner.$metadata$ = objectMeta("EquirippleDesigner");
      var EquirippleDesigner_instance;
      function EquirippleDesigner_getInstance() {
        if (EquirippleDesigner_instance == null)
          new EquirippleDesigner();
        return EquirippleDesigner_instance;
      }
      function Companion_7() {
        Companion_instance_7 = this;
        this.MACHINETOLERANCE_1 = 1e-6;
      }
      Companion_7.prototype.get_MACHINETOLERANCE_yw6kj3_k$ = function() {
        return this.MACHINETOLERANCE_1;
      };
      Companion_7.$metadata$ = objectMeta("Companion");
      Object.defineProperty(Companion_7.prototype, "MACHINETOLERANCE", {
        configurable: true,
        get: Companion_7.prototype.get_MACHINETOLERANCE_yw6kj3_k$
      });
      var Companion_instance_7;
      function Companion_getInstance_7() {
        if (Companion_instance_7 == null)
          new Companion_7();
        return Companion_instance_7;
      }
      function EquirippleFIRFilter2(numBands, N, Nc) {
        Companion_getInstance_7();
        this.numBands_1 = numBands;
        this.N_1 = N;
        this.Nc_1 = Nc;
        this._coefficients_1 = null;
        this.implementation_1 = null;
        var tmp = this;
        var tmp_0 = 0;
        var tmp_1 = this.numBands_1;
        var tmp$ret$0;
        tmp$ret$0 = fillArrayVal(Array(tmp_1), null);
        var tmp_2 = tmp$ret$0;
        while (tmp_0 < tmp_1) {
          var tmp_3 = tmp_0;
          var tmp$ret$1;
          tmp$ret$1 = new Float64Array(2);
          tmp_2[tmp_3] = tmp$ret$1;
          tmp_0 = tmp_0 + 1 | 0;
        }
        tmp.bands_1 = tmp_2;
      }
      EquirippleFIRFilter2.prototype.set_numBands_se5e1n_k$ = function(_set____db54di) {
        this.numBands_1 = _set____db54di;
      };
      EquirippleFIRFilter2.prototype.get_numBands_7jdbr5_k$ = function() {
        return this.numBands_1;
      };
      EquirippleFIRFilter2.prototype.set_N_hmx2g1_k$ = function(_set____db54di) {
        this.N_1 = _set____db54di;
      };
      EquirippleFIRFilter2.prototype.get_N_1mhr51_k$ = function() {
        return this.N_1;
      };
      EquirippleFIRFilter2.prototype.set_Nc_147wda_k$ = function(_set____db54di) {
        this.Nc_1 = _set____db54di;
      };
      EquirippleFIRFilter2.prototype.get_Nc_kntoki_k$ = function() {
        return this.Nc_1;
      };
      EquirippleFIRFilter2.prototype.set_bands_v2glr4_k$ = function(_set____db54di) {
        this.bands_1 = _set____db54di;
      };
      EquirippleFIRFilter2.prototype.get_bands_ip1jn9_k$ = function() {
        return this.bands_1;
      };
      EquirippleFIRFilter2.prototype.set__coefficients_wl2gmb_k$ = function(_set____db54di) {
        this._coefficients_1 = _set____db54di;
      };
      EquirippleFIRFilter2.prototype.get__coefficients_hv8wpg_k$ = function() {
        return this._coefficients_1;
      };
      EquirippleFIRFilter2.prototype.getCoefficients = function() {
        var tmp0_safe_receiver = this._coefficients_1;
        var tmp;
        if (tmp0_safe_receiver == null) {
          tmp = null;
        } else {
          var tmp$ret$1;
          var tmp$ret$0;
          tmp$ret$0 = tmp0_safe_receiver;
          tmp$ret$1 = tmp$ret$0.slice();
          tmp = tmp$ret$1;
        }
        var tmp1_elvis_lhs = tmp;
        var tmp_0;
        if (tmp1_elvis_lhs == null) {
          throw RuntimeException_init_$Create$("Should not happen, access to coefficients before initialized.");
        } else {
          tmp_0 = tmp1_elvis_lhs;
        }
        return tmp_0;
      };
      EquirippleFIRFilter2.prototype.set_implementation_v6iu10_k$ = function(_set____db54di) {
        this.implementation_1 = _set____db54di;
      };
      EquirippleFIRFilter2.prototype.get_implementation_9txf7p_k$ = function() {
        return this.implementation_1;
      };
      EquirippleFIRFilter2.prototype.createGrid = function() {
        var G = new DesignGrid();
        var nextrema = new Int32Array(this.numBands_1);
        var totalBandwidth = 0;
        var inductionVariable = 0;
        var last = this.numBands_1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var ib = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            totalBandwidth = totalBandwidth + (this.bands_1[ib][1] - this.bands_1[ib][0]);
          } while (!(ib === last));
        var m = (this.N_1 + 1 | 0) - imul(2, this.numBands_1) | 0;
        var np = 0;
        var largestBand = 0;
        var nmax = 0;
        var inductionVariable_0 = 0;
        var last_0 = this.numBands_1 - 1 | 0;
        if (inductionVariable_0 <= last_0)
          do {
            var ib_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            var B = this.bands_1[ib_0][1] - this.bands_1[ib_0][0];
            nextrema[ib_0] = numberToInt(round(m * B / totalBandwidth)) + 2 | 0;
            if (nextrema[ib_0] > nmax) {
              nmax = nextrema[ib_0];
              largestBand = ib_0;
            }
            np = np + nextrema[ib_0] | 0;
          } while (!(ib_0 === last_0));
        while (np < (this.N_1 + 1 | 0)) {
          var tmp2_array = nextrema;
          var tmp3_index0 = largestBand;
          var tmp4 = tmp2_array[tmp3_index0];
          tmp2_array[tmp3_index0] = tmp4 + 1 | 0;
          var tmp5 = np;
          np = tmp5 + 1 | 0;
        }
        while (np > (this.N_1 + 1 | 0)) {
          var tmp6_array = nextrema;
          var tmp7_index0 = largestBand;
          var tmp8 = tmp6_array[tmp7_index0];
          tmp6_array[tmp7_index0] = tmp8 - 1 | 0;
          var tmp9 = np;
          np = tmp9 - 1 | 0;
        }
        G.bandEdgeIndices_1 = new Int32Array(imul(this.numBands_1, 2));
        G.extremaIndices_1 = new Int32Array(this.N_1 + 1 | 0);
        var gridArray = ArrayList_init_$Create$();
        var gridpt = 0;
        var extremum = 0;
        var bandEdgeCount = 0;
        var perturbation;
        var inductionVariable_1 = 0;
        var last_1 = this.numBands_1 - 1 | 0;
        if (inductionVariable_1 <= last_1)
          do {
            var ib_1 = inductionVariable_1;
            inductionVariable_1 = inductionVariable_1 + 1 | 0;
            var B_0 = this.bands_1[ib_1][1] - this.bands_1[ib_1][0];
            var n2 = 1 + imul(nextrema[ib_1] - 1 | 0, Companion_getInstance_6().GRIDDENSITY_1) | 0;
            var dB = B_0 / (n2 - 1 | 0);
            var base = this.bands_1[ib_1][0];
            var inductionVariable_2 = 0;
            var last_2 = n2 - 1 | 0;
            if (inductionVariable_2 <= last_2)
              do {
                var i = inductionVariable_2;
                inductionVariable_2 = inductionVariable_2 + 1 | 0;
                var Omega = base + dB * i;
                gridArray.add_1j60pz_k$(Omega);
                if ((i % Companion_getInstance_6().GRIDDENSITY_1 | 0) === 0) {
                  if (!(i === 0) ? !(i === (n2 - 1 | 0)) : false) {
                    var tmp$ret$1;
                    var tmp$ret$0;
                    var tmp0_floor = Default_getInstance().nextFloat_jqti5l_k$() * 3;
                    tmp$ret$0 = Math.floor(tmp0_floor);
                    var tmp1_roundToInt = tmp$ret$0;
                    tmp$ret$1 = roundToInt(tmp1_roundToInt);
                    perturbation = tmp$ret$1 - 1 | 0;
                  } else
                    perturbation = 0;
                  var tmp = G.get_extremaIndices_8bux3s_k$();
                  var tmp12 = extremum;
                  extremum = tmp12 + 1 | 0;
                  tmp[tmp12] = gridpt + perturbation | 0;
                }
                if (i === 0 ? true : i === (n2 - 1 | 0)) {
                  G.get_bandEdgeIndices_4mq7kc_k$()[bandEdgeCount] = gridpt;
                  var tmp13 = bandEdgeCount;
                  bandEdgeCount = tmp13 + 1 | 0;
                }
                var tmp14 = gridpt;
                gridpt = tmp14 + 1 | 0;
              } while (!(i === last_2));
          } while (!(ib_1 === last_1));
        G.gridSize_1 = gridArray.get_size_woubt6_k$();
        G.grid_1 = new Float64Array(G.gridSize_1);
        G.X_1 = new Float64Array(G.gridSize_1);
        G.H_1 = new Float64Array(G.gridSize_1);
        G.W_1 = new Float64Array(G.gridSize_1);
        var inductionVariable_3 = 0;
        var last_3 = G.gridSize_1 - 1 | 0;
        if (inductionVariable_3 <= last_3)
          do {
            var i_0 = inductionVariable_3;
            inductionVariable_3 = inductionVariable_3 + 1 | 0;
            G.get_grid_womu8f_k$()[i_0] = gridArray.get_fkrdnv_k$(i_0);
            var tmp_0 = G.get_X_1mhr5b_k$();
            var tmp$ret$2;
            var tmp2_cos = G.get_grid_womu8f_k$()[i_0] * get_PI();
            tmp$ret$2 = Math.cos(tmp2_cos);
            tmp_0[i_0] = tmp$ret$2;
          } while (!(i_0 === last_3));
        return G;
      };
      EquirippleFIRFilter2.prototype.generateCoefficients = function() {
        var G = this.createGrid();
        this.populateGrid(G);
        EquirippleDesigner_getInstance().remez(G);
        this._coefficients_1 = this.interpretCoefficients(EquirippleDesigner_getInstance().calculateCoefficients(G, this.Nc_1));
      };
      EquirippleFIRFilter2.prototype.getImplementation = function(blockSize) {
        return OverlapAdd_ofArray(this.getCoefficients(), blockSize);
      };
      EquirippleFIRFilter2.prototype.filter = function(x2) {
        var nfft = 16;
        var log2nfft = 4;
        var coefficients = this.getCoefficients();
        var n2 = (x2.length + coefficients.length | 0) - 1 | 0;
        while (nfft < n2) {
          nfft = imul(nfft, 2);
          var tmp0 = log2nfft;
          log2nfft = tmp0 + 1 | 0;
        }
        var fft2 = new RDFT2(log2nfft);
        var tmp = new Float32Array(nfft);
        var transform2 = new Float32Array(nfft);
        var kernel = new Float32Array(nfft);
        var inductionVariable = 0;
        var last = x2.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            tmp[i] = x2[i];
          } while (inductionVariable <= last);
        fft2.evaluate(tmp, transform2);
        var inductionVariable_0 = 0;
        var last_0 = tmp.length - 1 | 0;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            tmp[i_0] = 0;
          } while (inductionVariable_0 <= last_0);
        var inductionVariable_1 = 0;
        var last_1 = coefficients.length - 1 | 0;
        if (inductionVariable_1 <= last_1)
          do {
            var i_1 = inductionVariable_1;
            inductionVariable_1 = inductionVariable_1 + 1 | 0;
            tmp[i_1] = coefficients[i_1];
          } while (inductionVariable_1 <= last_1);
        fft2.evaluate(tmp, kernel);
        Companion_getInstance_4().dftProduct(kernel, transform2, 1);
        fft2.evaluateInverse(transform2, tmp);
        kernel = new Float32Array(n2);
        var inductionVariable_2 = 0;
        if (inductionVariable_2 <= n2)
          do {
            var i_2 = inductionVariable_2;
            inductionVariable_2 = inductionVariable_2 + 1 | 0;
            kernel[i_2] = tmp[i_2];
          } while (!(i_2 === n2));
        return kernel;
      };
      EquirippleFIRFilter2.prototype.LTE = function(x2, y2) {
        var retval = false;
        if (x2 < y2)
          retval = true;
        var tmp$ret$0;
        var tmp0_abs = x2 - y2;
        tmp$ret$0 = Math.abs(tmp0_abs);
        if (tmp$ret$0 < Companion_getInstance_7().MACHINETOLERANCE_1)
          retval = true;
        return retval;
      };
      EquirippleFIRFilter2.$metadata$ = classMeta("EquirippleFIRFilter");
      Object.defineProperty(EquirippleFIRFilter2.prototype, "numBands", {
        configurable: true,
        get: EquirippleFIRFilter2.prototype.get_numBands_7jdbr5_k$,
        set: EquirippleFIRFilter2.prototype.set_numBands_se5e1n_k$
      });
      Object.defineProperty(EquirippleFIRFilter2.prototype, "N", {
        configurable: true,
        get: EquirippleFIRFilter2.prototype.get_N_1mhr51_k$,
        set: EquirippleFIRFilter2.prototype.set_N_hmx2g1_k$
      });
      Object.defineProperty(EquirippleFIRFilter2.prototype, "Nc", {
        configurable: true,
        get: EquirippleFIRFilter2.prototype.get_Nc_kntoki_k$,
        set: EquirippleFIRFilter2.prototype.set_Nc_147wda_k$
      });
      Object.defineProperty(EquirippleFIRFilter2.prototype, "bands", {
        configurable: true,
        get: EquirippleFIRFilter2.prototype.get_bands_ip1jn9_k$,
        set: EquirippleFIRFilter2.prototype.set_bands_v2glr4_k$
      });
      Object.defineProperty(EquirippleFIRFilter2.prototype, "_coefficients", {
        configurable: true,
        get: EquirippleFIRFilter2.prototype.get__coefficients_hv8wpg_k$,
        set: EquirippleFIRFilter2.prototype.set__coefficients_wl2gmb_k$
      });
      Object.defineProperty(EquirippleFIRFilter2.prototype, "implementation", {
        configurable: true,
        get: EquirippleFIRFilter2.prototype.get_implementation_9txf7p_k$,
        set: EquirippleFIRFilter2.prototype.set_implementation_v6iu10_k$
      });
      function _get_coefficients__vzgld9($this) {
        return $this.coefficients_1;
      }
      function EquirippleHalfBand2(N, OmegaP) {
        var EHBP = new EquirippleHalfBandPrototype(N, 2 * OmegaP);
        var c = EHBP.getCoefficients();
        this.coefficients_1 = new Float32Array(imul(2, c.length) - 1 | 0);
        var inductionVariable = 0;
        var last = c.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            this.coefficients_1[imul(2, i)] = 0.5 * c[i];
          } while (inductionVariable <= last);
        this.coefficients_1[c.length - 1 | 0] = 0.5;
      }
      EquirippleHalfBand2.prototype.getCoefficients = function() {
        var tmp$ret$1;
        var tmp0_copyOf = this.coefficients_1;
        var tmp$ret$0;
        tmp$ret$0 = tmp0_copyOf;
        tmp$ret$1 = tmp$ret$0.slice();
        return tmp$ret$1;
      };
      EquirippleHalfBand2.$metadata$ = classMeta("EquirippleHalfBand");
      function EquirippleHalfBandPrototype(N, OmegaP) {
        FIRTypeII2.call(this, 1, N);
        if (OmegaP <= 0 ? true : OmegaP >= 1)
          throw IllegalArgumentException_init_$Create$("OmegaP: " + OmegaP + " out of bounds (0.0 < OmegaP < 1.0)");
        this.bands_1[0][0] = 0;
        this.bands_1[0][1] = OmegaP;
        this.generateCoefficients();
      }
      EquirippleHalfBandPrototype.prototype.desiredResponse_yw2r0a_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = 1;
        return retval;
      };
      EquirippleHalfBandPrototype.prototype.desiredResponse = function(Omega) {
        return this.desiredResponse_yw2r0a_k$(Omega);
      };
      EquirippleHalfBandPrototype.prototype.weight_3hkr93_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = 1;
        return retval;
      };
      EquirippleHalfBandPrototype.prototype.weight = function(Omega) {
        return this.weight_3hkr93_k$(Omega);
      };
      EquirippleHalfBandPrototype.$metadata$ = classMeta("EquirippleHalfBandPrototype", void 0, void 0, void 0, void 0, FIRTypeII2.prototype);
      function _get_Ws__ndbq4v($this) {
        return $this.Ws_1;
      }
      function _get_Wp__ndbq2a_0($this) {
        return $this.Wp_1;
      }
      function EquirippleHighpass2(N, OmegaS, Ws, OmegaP, Wp) {
        FIRTypeI2.call(this, 2, N);
        this.Ws_1 = Ws;
        this.Wp_1 = Wp;
        if (OmegaS >= OmegaP)
          throw IllegalArgumentException_init_$Create$("OmegaS >= OmegaP ");
        if (OmegaS <= 0 ? true : OmegaS >= 1)
          throw IllegalArgumentException_init_$Create$("OmegaS: " + OmegaS + " out of bounds (0.0 < OmegaS < 1.0)");
        if (OmegaP <= 0 ? true : OmegaP >= 1)
          throw IllegalArgumentException_init_$Create$("OmegaP: " + OmegaP + " out of bounds (0.0 < OmegaP < 1.0)");
        this.bands_1[0][0] = 0;
        this.bands_1[0][1] = OmegaS;
        this.bands_1[1][0] = OmegaP;
        this.bands_1[1][1] = 1;
        this.generateCoefficients();
      }
      EquirippleHighpass2.prototype.desiredResponse_yw2r0a_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[1][0], Omega) ? this.LTE(Omega, this.bands_1[1][1]) : false)
          retval = 1;
        return retval;
      };
      EquirippleHighpass2.prototype.desiredResponse = function(Omega) {
        return this.desiredResponse_yw2r0a_k$(Omega);
      };
      EquirippleHighpass2.prototype.weight_3hkr93_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = this.Ws_1;
        else if (this.LTE(this.bands_1[1][0], Omega) ? this.LTE(Omega, this.bands_1[1][1]) : false)
          retval = this.Wp_1;
        return retval;
      };
      EquirippleHighpass2.prototype.weight = function(Omega) {
        return this.weight_3hkr93_k$(Omega);
      };
      EquirippleHighpass2.$metadata$ = classMeta("EquirippleHighpass", void 0, void 0, void 0, void 0, FIRTypeI2.prototype);
      function _get_Wp__ndbq2a_1($this) {
        return $this.Wp_1;
      }
      function _get_Ws__ndbq4v_0($this) {
        return $this.Ws_1;
      }
      function EquirippleLowpass2(N, OmegaP, Wp, OmegaS, Ws) {
        FIRTypeI2.call(this, 2, N);
        this.Wp_1 = Wp;
        this.Ws_1 = Ws;
        if (OmegaP >= OmegaS)
          throw IllegalArgumentException_init_$Create$("OmegaP >= OmegaS ");
        if (OmegaP <= 0 ? true : OmegaP >= 1)
          throw IllegalArgumentException_init_$Create$("OmegaP: " + OmegaP + " out of bounds (0.0 < OmegaP < 1.0)");
        if (OmegaS <= 0 ? true : OmegaS >= 1)
          throw IllegalArgumentException_init_$Create$("OmegaS: " + OmegaS + " out of bounds (0.0 < OmegaS < 1.0)");
        this.bands_1[0][0] = 0;
        this.bands_1[0][1] = OmegaP;
        this.bands_1[1][0] = OmegaS;
        this.bands_1[1][1] = 1;
        this.generateCoefficients();
      }
      EquirippleLowpass2.prototype.desiredResponse_yw2r0a_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = 1;
        return retval;
      };
      EquirippleLowpass2.prototype.desiredResponse = function(Omega) {
        return this.desiredResponse_yw2r0a_k$(Omega);
      };
      EquirippleLowpass2.prototype.weight_3hkr93_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = this.Wp_1;
        else if (this.LTE(this.bands_1[1][0], Omega) ? this.LTE(Omega, this.bands_1[1][1]) : false)
          retval = this.Ws_1;
        return retval;
      };
      EquirippleLowpass2.prototype.weight = function(Omega) {
        return this.weight_3hkr93_k$(Omega);
      };
      EquirippleLowpass2.$metadata$ = classMeta("EquirippleLowpass", void 0, void 0, void 0, void 0, FIRTypeI2.prototype);
      function FIRTypeI2(numBands, nHalf) {
        EquirippleFIRFilter2.call(this, numBands, nHalf + 1 | 0, imul(2, nHalf) + 1 | 0);
      }
      FIRTypeI2.prototype.populateGrid_wohwv6_k$ = function(G) {
        var inductionVariable = 0;
        var last = G.gridSize_1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            G.get_H_1mhr4v_k$()[i] = this.desiredResponse(G.get_grid_womu8f_k$()[i]);
            G.get_W_1mhr5a_k$()[i] = this.weight(G.get_grid_womu8f_k$()[i]);
          } while (!(i === last));
        G.containsZero_1 = true;
        G.containsPi_1 = true;
      };
      FIRTypeI2.prototype.populateGrid = function(G) {
        return this.populateGrid_wohwv6_k$(G);
      };
      FIRTypeI2.prototype.interpretCoefficients_ctexi_k$ = function(coefficients) {
        var retval = new Float32Array(this.Nc_1);
        Companion_getInstance().circularShiftArray(coefficients, this.N_1 - 1 | 0);
        var inductionVariable = 0;
        var last = this.Nc_1;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            retval[i] = coefficients[i];
          } while (!(i === last));
        return retval;
      };
      FIRTypeI2.prototype.interpretCoefficients = function(coefficients) {
        return this.interpretCoefficients_ctexi_k$(coefficients);
      };
      FIRTypeI2.$metadata$ = classMeta("FIRTypeI", void 0, void 0, void 0, void 0, EquirippleFIRFilter2.prototype);
      function FIRTypeII2(numBands, nHalf) {
        EquirippleFIRFilter2.call(this, numBands, nHalf, imul(2, nHalf));
      }
      FIRTypeII2.prototype.populateGrid_wohwv6_k$ = function(G) {
        var inductionVariable = 0;
        var last = G.gridSize_1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp = G.get_H_1mhr4v_k$();
            var tmp_0 = this.desiredResponse(G.get_grid_womu8f_k$()[i]);
            var tmp$ret$0;
            var tmp0_cos = G.get_grid_womu8f_k$()[i] * get_PI() / 2;
            tmp$ret$0 = Math.cos(tmp0_cos);
            tmp[i] = tmp_0 / tmp$ret$0;
            var tmp_1 = G.get_W_1mhr5a_k$();
            var tmp_2 = this.weight(G.get_grid_womu8f_k$()[i]);
            var tmp$ret$1;
            var tmp1_cos = G.get_grid_womu8f_k$()[i] * get_PI() / 2;
            tmp$ret$1 = Math.cos(tmp1_cos);
            tmp_1[i] = tmp_2 * tmp$ret$1;
          } while (!(i === last));
        var tmp$ret$2;
        var tmp2_abs = G.get_grid_womu8f_k$()[0];
        tmp$ret$2 = Math.abs(tmp2_abs);
        if (tmp$ret$2 < 1e-6)
          G.containsZero_1 = true;
        else {
          G.containsZero_1 = false;
        }
        G.containsPi_1 = false;
      };
      FIRTypeII2.prototype.populateGrid = function(G) {
        return this.populateGrid_wohwv6_k$(G);
      };
      FIRTypeII2.prototype.interpretCoefficients_ctexi_k$ = function(coefficients) {
        var retval = new Float32Array(this.Nc_1);
        Companion_getInstance().circularShiftArray(coefficients, this.N_1 - 1 | 0);
        retval[0] = 0.5 * coefficients[0];
        var inductionVariable = 1;
        var last = (this.Nc_1 - 1 | 0) - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            retval[i] = 0.5 * (coefficients[i] + coefficients[i - 1 | 0]);
          } while (!(i === last));
        retval[this.Nc_1 - 1 | 0] = 0.5 * coefficients[this.Nc_1 - 2 | 0];
        return retval;
      };
      FIRTypeII2.prototype.interpretCoefficients = function(coefficients) {
        return this.interpretCoefficients_ctexi_k$(coefficients);
      };
      FIRTypeII2.$metadata$ = classMeta("FIRTypeII", void 0, void 0, void 0, void 0, EquirippleFIRFilter2.prototype);
      function FIRTypeIII2(numBands, nHalf) {
        EquirippleFIRFilter2.call(this, numBands, nHalf, imul(2, nHalf) + 1 | 0);
      }
      FIRTypeIII2.prototype.populateGrid_wohwv6_k$ = function(G) {
        var inductionVariable = 0;
        var last = G.gridSize_1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp = G.get_H_1mhr4v_k$();
            var tmp_0 = this.desiredResponse(G.get_grid_womu8f_k$()[i]);
            var tmp$ret$0;
            var tmp0_sin = G.get_grid_womu8f_k$()[i] * get_PI();
            tmp$ret$0 = Math.sin(tmp0_sin);
            tmp[i] = tmp_0 / tmp$ret$0;
            var tmp_1 = G.get_W_1mhr5a_k$();
            var tmp_2 = this.weight(G.get_grid_womu8f_k$()[i]);
            var tmp$ret$1;
            var tmp1_sin = G.get_grid_womu8f_k$()[i] * get_PI();
            tmp$ret$1 = Math.sin(tmp1_sin);
            tmp_1[i] = tmp_2 * tmp$ret$1;
          } while (!(i === last));
        G.containsZero_1 = false;
        G.containsPi_1 = false;
      };
      FIRTypeIII2.prototype.populateGrid = function(G) {
        return this.populateGrid_wohwv6_k$(G);
      };
      FIRTypeIII2.prototype.interpretCoefficients_ctexi_k$ = function(coefficients) {
        var retval = new Float32Array(this.Nc_1);
        Companion_getInstance().circularShiftArray(coefficients, this.N_1 - 1 | 0);
        retval[0] = -0.5 * coefficients[0];
        retval[1] = -0.5 * coefficients[1];
        var inductionVariable = 2;
        var last = (this.Nc_1 - 2 | 0) - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            retval[i] = 0.5 * (coefficients[i - 2 | 0] - coefficients[i]);
          } while (!(i === last));
        retval[this.Nc_1 - 2 | 0] = 0.5 * coefficients[this.Nc_1 - 4 | 0];
        retval[this.Nc_1 - 1 | 0] = 0.5 * coefficients[this.Nc_1 - 3 | 0];
        return retval;
      };
      FIRTypeIII2.prototype.interpretCoefficients = function(coefficients) {
        return this.interpretCoefficients_ctexi_k$(coefficients);
      };
      FIRTypeIII2.$metadata$ = classMeta("FIRTypeIII", void 0, void 0, void 0, void 0, EquirippleFIRFilter2.prototype);
      function FIRTypeIV(numBands, nHalf) {
        EquirippleFIRFilter2.call(this, numBands, nHalf, imul(2, nHalf));
      }
      FIRTypeIV.prototype.populateGrid_wohwv6_k$ = function(G) {
        var inductionVariable = 0;
        var last = G.gridSize_1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var tmp = G.get_H_1mhr4v_k$();
            var tmp_0 = this.desiredResponse(G.get_grid_womu8f_k$()[i]);
            var tmp$ret$0;
            var tmp0_sin = G.get_grid_womu8f_k$()[i] * get_PI() / 2;
            tmp$ret$0 = Math.sin(tmp0_sin);
            tmp[i] = tmp_0 / tmp$ret$0;
            var tmp_1 = G.get_W_1mhr5a_k$();
            var tmp_2 = this.weight(G.get_grid_womu8f_k$()[i]);
            var tmp$ret$1;
            var tmp1_sin = G.get_grid_womu8f_k$()[i] * get_PI() / 2;
            tmp$ret$1 = Math.sin(tmp1_sin);
            tmp_1[i] = tmp_2 * tmp$ret$1;
          } while (!(i === last));
        G.containsZero_1 = false;
        var tmp$ret$2;
        var tmp2_abs = G.get_grid_womu8f_k$()[G.gridSize_1 - 1 | 0] - 1;
        tmp$ret$2 = Math.abs(tmp2_abs);
        if (tmp$ret$2 < 1e-6)
          G.containsPi_1 = true;
        else {
          G.containsPi_1 = false;
        }
      };
      FIRTypeIV.prototype.populateGrid = function(G) {
        return this.populateGrid_wohwv6_k$(G);
      };
      FIRTypeIV.prototype.interpretCoefficients_ctexi_k$ = function(coefficients) {
        var retval = new Float32Array(this.Nc_1);
        Companion_getInstance().circularShiftArray(coefficients, this.N_1 - 1 | 0);
        retval[0] = -0.5 * coefficients[0];
        var inductionVariable = 1;
        var last = (this.Nc_1 - 1 | 0) - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            retval[i] = 0.5 * (coefficients[i - 1 | 0] - coefficients[i]);
          } while (!(i === last));
        retval[this.Nc_1 - 1 | 0] = 0.5 * coefficients[this.Nc_1 - 2 | 0];
        return retval;
      };
      FIRTypeIV.prototype.interpretCoefficients = function(coefficients) {
        return this.interpretCoefficients_ctexi_k$(coefficients);
      };
      FIRTypeIV.$metadata$ = classMeta("FIRTypeIV", void 0, void 0, void 0, void 0, EquirippleFIRFilter2.prototype);
      function _get_delta__ikpko7_0($this) {
        return $this.delta_1;
      }
      function StaggeredDifferentiator2(N, delta) {
        FIRTypeIV.call(this, 1, N);
        this.delta_1 = delta;
        this.bands_1[0][0] = 1 / imul(2, N);
        this.bands_1[0][1] = 1;
        this.generateCoefficients();
      }
      StaggeredDifferentiator2.prototype.desiredResponse_yw2r0a_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = -get_PI() * Omega / this.delta_1;
        return retval;
      };
      StaggeredDifferentiator2.prototype.desiredResponse = function(Omega) {
        return this.desiredResponse_yw2r0a_k$(Omega);
      };
      StaggeredDifferentiator2.prototype.weight_3hkr93_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = 1 / Omega;
        return retval;
      };
      StaggeredDifferentiator2.prototype.weight = function(Omega) {
        return this.weight_3hkr93_k$(Omega);
      };
      StaggeredDifferentiator2.$metadata$ = classMeta("StaggeredDifferentiator", void 0, void 0, void 0, void 0, FIRTypeIV.prototype);
      function StaggeredHilbertTranform2(N, OmegaP) {
        FIRTypeIV.call(this, 1, N);
        if (!(0 < OmegaP ? OmegaP < 1 : false))
          throw IllegalArgumentException_init_$Create$("Check 0.0 < OmegaP < 1.0");
        this.bands_1[0][0] = OmegaP;
        this.bands_1[0][1] = 1;
        this.generateCoefficients();
      }
      StaggeredHilbertTranform2.prototype.desiredResponse_yw2r0a_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = 1;
        return retval;
      };
      StaggeredHilbertTranform2.prototype.desiredResponse = function(Omega) {
        return this.desiredResponse_yw2r0a_k$(Omega);
      };
      StaggeredHilbertTranform2.prototype.weight_3hkr93_k$ = function(Omega) {
        var retval = 0;
        if (this.LTE(this.bands_1[0][0], Omega) ? this.LTE(Omega, this.bands_1[0][1]) : false)
          retval = 1;
        return retval;
      };
      StaggeredHilbertTranform2.prototype.weight = function(Omega) {
        return this.weight_3hkr93_k$(Omega);
      };
      StaggeredHilbertTranform2.$metadata$ = classMeta("StaggeredHilbertTranform", void 0, void 0, void 0, void 0, FIRTypeIV.prototype);
      function Allpass_init_$Init$(A, $this) {
        Allpass2.call($this, A.reflectionCoefficients().length);
        $this.k_1 = A.reflectionCoefficients();
        $this.state_1 = new Float64Array($this.order_1 + 1 | 0);
        $this.constructRationalRepresentation();
        return $this;
      }
      function Allpass_ofPolynomial(A) {
        return Allpass_init_$Init$(A, Object.create(Allpass2.prototype));
      }
      function Allpass_init_$Init$_0(k, $this) {
        Allpass2.call($this, k.length);
        var tmp = $this;
        var tmp$ret$1;
        var tmp$ret$0;
        tmp$ret$0 = k;
        tmp$ret$1 = tmp$ret$0.slice();
        tmp.k_1 = tmp$ret$1;
        $this.order_1 = $this.k_1.length;
        $this.state_1 = new Float64Array($this.order_1 + 1 | 0);
        $this.constructRationalRepresentation();
        return $this;
      }
      function Allpass_ofArray(k) {
        return Allpass_init_$Init$_0(k, Object.create(Allpass2.prototype));
      }
      function Allpass2(filterorder) {
        this.order_1 = filterorder;
        this.k_1 = new Float64Array(this.order_1);
        this.state_1 = new Float64Array(this.order_1 + 1 | 0);
        this.constructRationalRepresentation();
      }
      Allpass2.prototype.set_k_3rn45h_k$ = function(_set____db54di) {
        this.k_1 = _set____db54di;
      };
      Allpass2.prototype.get_k_1mhr5u_k$ = function() {
        return this.k_1;
      };
      Allpass2.prototype.set_order_nhlmht_k$ = function(_set____db54di) {
        this.order_1 = _set____db54di;
      };
      Allpass2.prototype.get_order_iwhiqt_k$ = function() {
        return this.order_1;
      };
      Allpass2.prototype.set_state_4gdqnf_k$ = function(_set____db54di) {
        this.state_1 = _set____db54di;
      };
      Allpass2.prototype.get_state_iypx7s_k$ = function() {
        return this.state_1;
      };
      Allpass2.prototype.set_T_dortqy_k$ = function(_set____db54di) {
        this.T_1 = _set____db54di;
      };
      Allpass2.prototype.get_T_1mhr57_k$ = function() {
        var tmp = this.T_1;
        if (!(tmp == null))
          return tmp;
        else {
          throwUninitializedPropertyAccessException("T");
        }
      };
      Allpass2.prototype.initialize = function() {
        var inductionVariable = 0;
        var last = this.state_1.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            this.state_1[i] = 0;
          } while (inductionVariable <= last);
      };
      Allpass2.prototype.filterSingle = function(x2) {
        var myX = x2;
        var stage = this.order_1;
        while (stage >= 0) {
          if (stage > 0) {
            myX = myX - this.k_1[stage - 1 | 0] * this.state_1[stage - 1 | 0];
            this.state_1[stage] = this.k_1[stage - 1 | 0] * myX + this.state_1[stage - 1 | 0];
          } else {
            this.state_1[stage] = myX;
          }
          var tmp0 = stage;
          stage = tmp0 - 1 | 0;
        }
        return this.state_1[this.order_1];
      };
      Allpass2.prototype.filter = function(x2) {
        var inductionVariable = 0;
        var last = x2.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            x2[i] = this.filterSingle(x2[i]);
          } while (inductionVariable <= last);
      };
      Allpass2.prototype.evaluate = function(omega) {
        var ejOmega = Companion_getInstance_8().exp(new Complex2(0, -omega));
        return this.T.evaluateComplex(ejOmega);
      };
      Allpass2.prototype.groupDelay = function(Omega) {
        return this.T.discreteTimeGroupDelay(Omega);
      };
      Allpass2.prototype.constructRationalRepresentation = function() {
        var a = new Float64Array(this.order_1 + 1 | 0);
        var b = new Float64Array(this.order_1 + 1 | 0);
        a[0] = 1;
        var inductionVariable = 0;
        var last = this.order_1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var p = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var inductionVariable_0 = 0;
            var last_0 = b.length - 1 | 0;
            if (inductionVariable_0 <= last_0)
              do {
                var j = inductionVariable_0;
                inductionVariable_0 = inductionVariable_0 + 1 | 0;
                b[j] = 0;
              } while (inductionVariable_0 <= last_0);
            var i = 0;
            while (i <= p) {
              var tmp2_array = b;
              var tmp3_index0 = i;
              tmp2_array[tmp3_index0] = tmp2_array[tmp3_index0] + a[i];
              var tmp4_array = b;
              var tmp5_index0 = i + 1 | 0;
              tmp4_array[tmp5_index0] = tmp4_array[tmp5_index0] + this.k_1[p] * a[p - i | 0];
              var tmp6 = i;
              i = tmp6 + 1 | 0;
            }
            var inductionVariable_1 = 0;
            var last_1 = p + 2 | 0;
            if (inductionVariable_1 <= last_1)
              do {
                var k = inductionVariable_1;
                inductionVariable_1 = inductionVariable_1 + 1 | 0;
                a[k] = b[k];
              } while (!(k === last_1));
          } while (!(p === last));
        var inductionVariable_2 = 0;
        var last_2 = b.length - 1 | 0;
        if (inductionVariable_2 <= last_2)
          do {
            var j_0 = inductionVariable_2;
            inductionVariable_2 = inductionVariable_2 + 1 | 0;
            b[j_0] = 0;
          } while (inductionVariable_2 <= last_2);
        var inductionVariable_3 = 0;
        var last_3 = this.order_1;
        if (inductionVariable_3 <= last_3)
          do {
            var i_0 = inductionVariable_3;
            inductionVariable_3 = inductionVariable_3 + 1 | 0;
            b[i_0] = a[this.order_1 - i_0 | 0];
          } while (!(i_0 === last_3));
        this.T_1 = Rational_ofPolynomials(Polynomial_ofArray(b), Polynomial_ofArray(a));
      };
      Allpass2.prototype.rationalRepresentation = function() {
        return Rational_ofRational(this.T);
      };
      Allpass2.prototype.toString = function() {
        var out = "Allpass _order:  " + this.order_1 + new Char(_Char___init__impl__6a9atx(10));
        var inductionVariable = 0;
        var last = this.order_1 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            if (i < this.order_1) {
              if (this.k_1[i] < 0)
                out = out + ("  " + this.k_1[i] + "  " + this.state_1[i] + new Char(_Char___init__impl__6a9atx(10)));
              else
                out = out + ("   " + this.k_1[i] + "  " + this.state_1[i] + new Char(_Char___init__impl__6a9atx(10)));
            } else
              out = out + ("             " + this.state_1[i] + new Char(_Char___init__impl__6a9atx(10)));
          } while (!(i === last));
        return out;
      };
      Allpass2.$metadata$ = classMeta("Allpass");
      Object.defineProperty(Allpass2.prototype, "k", {
        configurable: true,
        get: Allpass2.prototype.get_k_1mhr5u_k$,
        set: Allpass2.prototype.set_k_3rn45h_k$
      });
      Object.defineProperty(Allpass2.prototype, "order", {
        configurable: true,
        get: Allpass2.prototype.get_order_iwhiqt_k$,
        set: Allpass2.prototype.set_order_nhlmht_k$
      });
      Object.defineProperty(Allpass2.prototype, "state", {
        configurable: true,
        get: Allpass2.prototype.get_state_iypx7s_k$,
        set: Allpass2.prototype.set_state_4gdqnf_k$
      });
      Object.defineProperty(Allpass2.prototype, "T", {
        configurable: true,
        get: Allpass2.prototype.get_T_1mhr57_k$,
        set: Allpass2.prototype.set_T_dortqy_k$
      });
      function AnalogButterworth(order) {
        AnalogPrototype2.call(this);
        var nRealPoles = order - imul(2, order / 2 | 0) | 0;
        var nComplexPolePairs = order / 2 | 0;
        var nPoles = nRealPoles + imul(2, nComplexPolePairs) | 0;
        if (nRealPoles === 1) {
          var tmp$ret$0;
          tmp$ret$0 = new Float64Array([1, 1]);
          var td = tmp$ret$0;
          this.addSection(Rational_ofPolynomials(Polynomial_ofConstant(1), Polynomial_ofArray(td)));
        }
        var dAngle = get_PI() / nPoles;
        var inductionVariable = 0;
        var last = nComplexPolePairs - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var angle = -get_PI() / 2 + dAngle / 2 * (1 + nRealPoles | 0) + i * dAngle;
            var tmp$ret$2;
            var tmp$ret$1;
            tmp$ret$1 = Math.sin(angle);
            var tmp0_doubleArrayOf = new Float64Array([1, -2 * tmp$ret$1, 1]);
            tmp$ret$2 = tmp0_doubleArrayOf;
            var td_0 = tmp$ret$2;
            this.addSection(Rational_ofPolynomials(Polynomial_ofConstant(1), Polynomial_ofArray(td_0)));
          } while (!(i === last));
      }
      AnalogButterworth.$metadata$ = classMeta("AnalogButterworth", void 0, void 0, void 0, void 0, AnalogPrototype2.prototype);
      function AnalogChebyshevI(order, epsilon3) {
        AnalogPrototype2.call(this);
        var tmp$ret$0;
        var tmp0_sqrt = 1 + epsilon3 * epsilon3;
        tmp$ret$0 = Math.sqrt(tmp0_sqrt);
        var alpha = (1 + tmp$ret$0) / epsilon3;
        var tmp$ret$1;
        var tmp1_pow = 1 / order;
        tmp$ret$1 = Math.pow(alpha, tmp1_pow);
        var p = tmp$ret$1;
        var a = 0.5 * (p - 1 / p);
        var b = 0.5 * (p + 1 / p);
        println("alpha: " + alpha);
        println("p:     " + p);
        println("a:     " + a);
        println("b:     " + b);
        var nRealPoles = order - imul(2, order / 2 | 0) | 0;
        var nComplexPolePairs = order / 2 | 0;
        var nPoles = nRealPoles + imul(2, nComplexPolePairs) | 0;
        if (nRealPoles === 1) {
          var tmp$ret$2;
          tmp$ret$2 = new Float64Array([a, 1]);
          var td = tmp$ret$2;
          this.addSection(Rational_ofPolynomials(Polynomial_ofConstant(1), Polynomial_ofArray(td)));
        }
        var dAngle = get_PI() / nPoles;
        var inductionVariable = 0;
        var last = nComplexPolePairs - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var angle = -get_PI() / 2 + dAngle / 2 * (1 + nRealPoles | 0) + i * dAngle;
            var tmp$ret$3;
            tmp$ret$3 = Math.sin(angle);
            var tmp = a * tmp$ret$3;
            var tmp$ret$4;
            tmp$ret$4 = Math.cos(angle);
            var pole = new Complex2(tmp, b * tmp$ret$4);
            var tmp$ret$5;
            var tmp2_doubleArrayOf = new Float64Array([pole.real() * pole.real() + pole.imag() * pole.imag(), -2 * pole.real(), 1]);
            tmp$ret$5 = tmp2_doubleArrayOf;
            var td_0 = tmp$ret$5;
            this.addSection(Rational_ofPolynomials(Polynomial_ofConstant(1), Polynomial_ofArray(td_0)));
          } while (!(i === last));
        var tmp_0 = this.sections_1.get_fkrdnv_k$(0);
        var tmp$ret$6;
        var tmp3_pow = order - 1 | 0;
        tmp$ret$6 = Math.pow(2, tmp3_pow);
        tmp_0.timesEqualsReal(1 / (tmp$ret$6 * epsilon3));
      }
      AnalogChebyshevI.$metadata$ = classMeta("AnalogChebyshevI", void 0, void 0, void 0, void 0, AnalogPrototype2.prototype);
      function AnalogChebyshevII(order, epsilon3) {
        AnalogPrototype2.call(this);
        var tmp$ret$0;
        var tmp0_sqrt = 1 + epsilon3 * epsilon3;
        tmp$ret$0 = Math.sqrt(tmp0_sqrt);
        var alpha = (1 + tmp$ret$0) / epsilon3;
        var tmp$ret$1;
        var tmp1_pow = 1 / order;
        tmp$ret$1 = Math.pow(alpha, tmp1_pow);
        var p = tmp$ret$1;
        var a = 0.5 * (p - 1 / p);
        var b = 0.5 * (p + 1 / p);
        println("alpha: " + alpha);
        println("p:     " + p);
        println("a:     " + a);
        println("b:     " + b);
        var nRealPoles = order - imul(2, order / 2 | 0) | 0;
        var nComplexPolePairs = order / 2 | 0;
        var nPoles = nRealPoles + imul(2, nComplexPolePairs) | 0;
        if (nRealPoles === 1) {
          var tmp$ret$2;
          var tmp2_doubleArrayOf = new Float64Array([1 / a, 1]);
          tmp$ret$2 = tmp2_doubleArrayOf;
          var td = tmp$ret$2;
          this.addSection(Rational_ofPolynomials(Polynomial_ofConstant(1), Polynomial_ofArray(td)));
        }
        var dAngle = get_PI() / nPoles;
        var inductionVariable = 0;
        var last = nComplexPolePairs - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var angle = -get_PI() / 2 + dAngle / 2 * (1 + nRealPoles | 0) + i * dAngle;
            var tmp = Companion_getInstance_8();
            var tmp$ret$3;
            tmp$ret$3 = Math.sin(angle);
            var tmp_0 = a * tmp$ret$3;
            var tmp$ret$4;
            tmp$ret$4 = Math.cos(angle);
            var pole = tmp.divideRealComplex(1, new Complex2(tmp_0, b * tmp$ret$4));
            var tmp$ret$5;
            var tmp3_doubleArrayOf = new Float64Array([pole.real() * pole.real() + pole.imag() * pole.imag(), -2 * pole.real(), 1]);
            tmp$ret$5 = tmp3_doubleArrayOf;
            var td_0 = tmp$ret$5;
            var tmp$ret$6;
            var tmp4_cos = (imul(2, i) + 1 | 0) * get_PI() / imul(2, order);
            tmp$ret$6 = Math.cos(tmp4_cos);
            var zeroimag = 1 / tmp$ret$6;
            var tmp$ret$7;
            var tmp5_doubleArrayOf = new Float64Array([zeroimag * zeroimag, 0, 1]);
            tmp$ret$7 = tmp5_doubleArrayOf;
            var tn = tmp$ret$7;
            this.addSection(Rational_ofPolynomials(Polynomial_ofArray(tn), Polynomial_ofArray(td_0)));
          } while (!(i === last));
        var DCvalue = this.evaluate(0).abs();
        this.sections_1.get_fkrdnv_k$(0).timesEqualsReal(1 / DCvalue);
      }
      AnalogChebyshevII.$metadata$ = classMeta("AnalogChebyshevII", void 0, void 0, void 0, void 0, AnalogPrototype2.prototype);
      function _set__T__dl8vxa($this, _set____db54di) {
        $this._T_1 = _set____db54di;
      }
      function _get__T__ndbvbq($this) {
        return $this._T_1;
      }
      function lptobpFactors($this, P, BW, prod) {
        var p = P.coefficients();
        var c = p[0] / p[2];
        var b = p[1] / p[2];
        var discriminant = b * b - 4 * c;
        var t02;
        var t12;
        if (discriminant >= 0) {
          var tmp = -b;
          var tmp$ret$0;
          tmp$ret$0 = Math.sqrt(discriminant);
          var root2 = (tmp + tmp$ret$0) / 2;
          var f1 = root2 * BW / 2;
          var f2 = f1 * f1 - prod;
          var C = Complex_fromReal(f1).plusComplex(Companion_getInstance_8().sqrt(Complex_fromReal(f2)));
          var tmp$ret$1;
          var tmp0_doubleArrayOf = new Float64Array([C.conjugate().timesComplex(C).real(), -2 * C.real(), 1]);
          tmp$ret$1 = tmp0_doubleArrayOf;
          t02 = Polynomial_ofArray(tmp$ret$1);
          var tmp_0 = -b;
          var tmp$ret$2;
          tmp$ret$2 = Math.sqrt(discriminant);
          root2 = (tmp_0 - tmp$ret$2) / 2;
          f1 = root2 * BW / 2;
          f2 = f1 * f1 - prod;
          C = Complex_fromReal(f1).plusComplex(Companion_getInstance_8().sqrt(Complex_fromReal(f2)));
          var tmp$ret$3;
          var tmp1_doubleArrayOf = new Float64Array([C.conjugate().timesComplex(C).real(), -2 * C.real(), 1]);
          tmp$ret$3 = tmp1_doubleArrayOf;
          t12 = Polynomial_ofArray(tmp$ret$3);
        } else {
          var tmp_1 = -b / 2;
          var tmp$ret$4;
          var tmp2_sqrt = -discriminant;
          tmp$ret$4 = Math.sqrt(tmp2_sqrt);
          var root_0 = new Complex2(tmp_1, tmp$ret$4 / 2);
          var f1_0 = root_0.timesReal(BW / 2);
          var f2_0 = f1_0.timesComplex(f1_0).minusReal(prod);
          var C_0 = f1_0.plusComplex(Companion_getInstance_8().sqrt(f2_0));
          var tmp$ret$5;
          var tmp3_doubleArrayOf = new Float64Array([C_0.conjugate().timesComplex(C_0).real(), -2 * C_0.real(), 1]);
          tmp$ret$5 = tmp3_doubleArrayOf;
          t02 = Polynomial_ofArray(tmp$ret$5);
          C_0 = f1_0.minusComplex(Companion_getInstance_8().sqrt(f2_0));
          var tmp$ret$6;
          var tmp4_doubleArrayOf = new Float64Array([C_0.conjugate().timesComplex(C_0).real(), -2 * C_0.real(), 1]);
          tmp$ret$6 = tmp4_doubleArrayOf;
          t12 = Polynomial_ofArray(tmp$ret$6);
        }
        var tmp$ret$9;
        var tmp5_arrayOf = [Polynomial_ofPolynomial(t02), Polynomial_ofPolynomial(t12)];
        var tmp$ret$8;
        var tmp$ret$7;
        tmp$ret$7 = tmp5_arrayOf;
        tmp$ret$8 = tmp$ret$7;
        tmp$ret$9 = tmp$ret$8;
        return tmp$ret$9;
      }
      function AnalogPrototype2() {
        this._T_1 = null;
        this.sections_1 = ArrayList_init_$Create$();
      }
      AnalogPrototype2.prototype.set_sections_8qbcpz_k$ = function(_set____db54di) {
        this.sections_1 = _set____db54di;
      };
      AnalogPrototype2.prototype.get_sections_g4k5xl_k$ = function() {
        return this.sections_1;
      };
      AnalogPrototype2.prototype.get_T_1mhr57_k$ = function() {
        if (this._T_1 == null) {
          this._T_1 = this.computeTransferFunction();
        }
        var tmp0_elvis_lhs = this._T_1;
        var tmp;
        if (tmp0_elvis_lhs == null) {
          throw RuntimeException_init_$Create$("SHould not happen, _T is null");
        } else {
          tmp = tmp0_elvis_lhs;
        }
        return tmp;
      };
      AnalogPrototype2.prototype.addSection = function(R) {
        this.sections_1.add_1j60pz_k$(R);
        this._T_1 = null;
      };
      AnalogPrototype2.prototype.nSections = function() {
        return this.sections_1.get_size_woubt6_k$();
      };
      AnalogPrototype2.prototype.getSection = function(index) {
        return Rational_ofRational(this.sections_1.get_fkrdnv_k$(index));
      };
      AnalogPrototype2.prototype.lptolp = function(omega0) {
        var tmp$ret$0;
        tmp$ret$0 = new Float64Array([0, 1]);
        var tn = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = new Float64Array([omega0]);
        var td = tmp$ret$1;
        var T = Rational_ofArrays(tn, td);
        var retval = new AnalogPrototype2();
        var inductionVariable = 0;
        var last = this.sections_1.get_size_woubt6_k$() - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            retval.addSection(this.sections_1.get_fkrdnv_k$(i).mapRational(T));
          } while (inductionVariable <= last);
        return retval;
      };
      AnalogPrototype2.prototype.lptohp = function(omega0) {
        var tmp$ret$0;
        tmp$ret$0 = new Float64Array([omega0]);
        var tn = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = new Float64Array([0, 1]);
        var td = tmp$ret$1;
        var T = Rational_ofArrays(tn, td);
        var retval = new AnalogPrototype2();
        var inductionVariable = 0;
        var last = this.sections_1.get_size_woubt6_k$() - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            retval.addSection(this.sections_1.get_fkrdnv_k$(i).mapRational(T));
          } while (inductionVariable <= last);
        return retval;
      };
      AnalogPrototype2.prototype.lptobp = function(omega1, omega2) {
        var BW = omega2 - omega1;
        var prod = omega1 * omega2;
        var tmp$ret$0;
        tmp$ret$0 = new Float64Array([prod, 0, 1]);
        var tn = tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = new Float64Array([0, BW]);
        var td = tmp$ret$1;
        var T = Rational_ofArrays(tn, td);
        var retval = new AnalogPrototype2();
        var A = 1;
        var inductionVariable = 0;
        var last = this.sections_1.get_size_woubt6_k$() - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var section = this.sections_1.get_fkrdnv_k$(i);
            var Tsection = section.mapRational(T);
            A = A * Tsection.canonicalForm();
            var order = section.order();
            if (order[0] < 2 ? order[1] < 2 : false) {
              retval.addSection(Tsection);
            } else if (order[1] === 2) {
              var DT = lptobpFactors(this, section.denominator(), BW, prod);
              var tmp$ret$2;
              tmp$ret$2 = new Float64Array([0, 1]);
              var t12 = tmp$ret$2;
              if (order[0] === 0) {
                retval.addSection(Rational_ofPolynomials(Polynomial_ofArray(t12), DT[0]));
                retval.addSection(Rational_ofPolynomials(Polynomial_ofArray(t12), DT[1]));
              } else if (order[0] === 1) {
                retval.addSection(Rational_ofPolynomials(Polynomial_ofArray(t12), DT[0]));
                var t2 = new Float64Array(3);
                var tc = Tsection.numerator().coefficients();
                var inductionVariable_0 = 0;
                if (inductionVariable_0 <= 2)
                  do {
                    var j = inductionVariable_0;
                    inductionVariable_0 = inductionVariable_0 + 1 | 0;
                    t2[j] = tc[j + 1 | 0];
                  } while (inductionVariable_0 <= 2);
                retval.addSection(Rational_ofPolynomials(Polynomial_ofArray(t2), DT[1]));
              } else if (order[0] === 2) {
                var NT = lptobpFactors(this, section.numerator(), BW, prod);
                retval.addSection(Rational_ofPolynomials(NT[0], DT[0]));
                retval.addSection(Rational_ofPolynomials(NT[1], DT[1]));
              }
            }
          } while (inductionVariable <= last);
        retval.sections_1.get_fkrdnv_k$(0).timesEqualsReal(A);
        return retval;
      };
      AnalogPrototype2.prototype.computeTransferFunction = function() {
        var T = Rational_ofConstant(1);
        var inductionVariable = 0;
        var last = this.sections_1.get_size_woubt6_k$() - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            T.timesEqualsRational(this.sections_1.get_fkrdnv_k$(i));
          } while (inductionVariable <= last);
        return T;
      };
      AnalogPrototype2.prototype.get_transferFunction_b52pik_k$ = function() {
        return Rational_ofRational(this.T);
      };
      AnalogPrototype2.prototype.evaluate = function(omega) {
        return this.T.evaluateComplex(new Complex2(0, omega));
      };
      AnalogPrototype2.prototype.groupDelay = function(omega) {
        return this.T.groupDelay(omega);
      };
      AnalogPrototype2.prototype.toString = function() {
        var out = "AnalogPrototype: \n";
        var inductionVariable = 0;
        var last = this.sections_1.get_size_woubt6_k$() - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            out = out + ("  section " + i + ":" + new Char(_Char___init__impl__6a9atx(10)));
            out = out + this.sections_1.get_fkrdnv_k$(i);
          } while (inductionVariable <= last);
        return out;
      };
      AnalogPrototype2.$metadata$ = classMeta("AnalogPrototype");
      Object.defineProperty(AnalogPrototype2.prototype, "sections", {
        configurable: true,
        get: AnalogPrototype2.prototype.get_sections_g4k5xl_k$,
        set: AnalogPrototype2.prototype.set_sections_8qbcpz_k$
      });
      Object.defineProperty(AnalogPrototype2.prototype, "T", {
        configurable: true,
        get: AnalogPrototype2.prototype.get_T_1mhr57_k$
      });
      Object.defineProperty(AnalogPrototype2.prototype, "transferFunction", {
        configurable: true,
        get: AnalogPrototype2.prototype.get_transferFunction_b52pik_k$
      });
      function Butterworth2(order, type, f1, f2, delta) {
        IIRFilter3.call(this, new AnalogButterworth(order), type, f1, f2, delta);
      }
      Butterworth2.$metadata$ = classMeta("Butterworth", void 0, void 0, void 0, void 0, IIRFilter3.prototype);
      function ChebyshevI2(order, epsilon3, type, f1, f2, delta) {
        IIRFilter3.call(this, new AnalogChebyshevI(order, epsilon3), type, f1, f2, delta);
      }
      ChebyshevI2.$metadata$ = classMeta("ChebyshevI", void 0, void 0, void 0, void 0, IIRFilter3.prototype);
      function ChebyshevII2(order, epsilon3, type, f1, f2, delta) {
        IIRFilter3.call(this, new AnalogChebyshevII(order, epsilon3), type, f1, f2, delta);
      }
      ChebyshevII2.$metadata$ = classMeta("ChebyshevII", void 0, void 0, void 0, void 0, IIRFilter3.prototype);
      function _set_real__9t9mrd($this, _set____db54di) {
        $this.real_1 = _set____db54di;
      }
      function _get_real__dd1mct($this) {
        return $this.real_1;
      }
      function _set_imag__9ogl71($this, _set____db54di) {
        $this.imag_1 = _set____db54di;
      }
      function _get_imag__d88ksh($this) {
        return $this.imag_1;
      }
      function Complex_init_$Init$(real, $this) {
        Complex2.call($this, real, 0);
        return $this;
      }
      function Complex_fromReal(real) {
        return Complex_init_$Init$(real, Object.create(Complex2.prototype));
      }
      function Companion_8() {
        Companion_instance_8 = this;
      }
      Companion_8.prototype.ComplexFromPolar = function(r, phi) {
        var tmp$ret$0;
        tmp$ret$0 = Math.cos(phi);
        var tmp = r * tmp$ret$0;
        var tmp$ret$1;
        tmp$ret$1 = Math.sin(phi);
        return new Complex2(tmp, r * tmp$ret$1);
      };
      Companion_8.prototype.addRealComplex = function(a, c) {
        return new Complex2(a + c.real_1, c.imag_1);
      };
      Companion_8.prototype.addComplexReal = function(c, a) {
        return this.addRealComplex(a, c);
      };
      Companion_8.prototype.subtractComplexReal = function(c, a) {
        return new Complex2(c.real_1 - a, c.imag_1);
      };
      Companion_8.prototype.subtractRealComplex = function(a, c) {
        return new Complex2(a - c.real_1, c.imag_1);
      };
      Companion_8.prototype.unaryMinus = function(c) {
        return new Complex2(-c.real_1, -c.imag_1);
      };
      Companion_8.prototype.multiplyRealComplex = function(a, c) {
        return new Complex2(a * c.real_1, a * c.imag_1);
      };
      Companion_8.prototype.multiplyComplexReal = function(c, a) {
        return this.multiplyRealComplex(a, c);
      };
      Companion_8.prototype.addComplexComplex = function(c1, c2) {
        return new Complex2(c1.real_1 + c2.real_1, c1.imag_1 + c2.imag_1);
      };
      Companion_8.prototype.subtractComplexComplex = function(c1, c2) {
        return new Complex2(c1.real_1 - c2.real_1, c1.imag_1 - c2.imag_1);
      };
      Companion_8.prototype.multiplyComplexComplex = function(c1, c2) {
        return new Complex2(c1.real_1 * c2.real_1 - c1.imag_1 * c2.imag_1, c1.real_1 * c2.imag_1 + c1.imag_1 * c2.real_1);
      };
      Companion_8.prototype.divideComplexReal = function(c, a) {
        return new Complex2(c.real_1 / a, c.imag_1 / a);
      };
      Companion_8.prototype.divideRealComplex = function(a, c) {
        var scale = c.real_1 * c.real_1 + c.imag_1 * c.imag_1;
        return new Complex2(a * c.real_1 / scale, a * -c.imag_1 / scale);
      };
      Companion_8.prototype.divideComplexComplex = function(c1, c2) {
        var scale = c2.real_1 * c2.real_1 + c2.imag_1 * c2.imag_1;
        return new Complex2((c1.real_1 * c2.real_1 + c1.imag_1 * c2.imag_1) / scale, (c1.imag_1 * c2.real_1 - c1.real_1 * c2.imag_1) / scale);
      };
      Companion_8.prototype.sqrt = function(c) {
        var tmp$ret$0;
        var tmp0_sqrt = this.abs(c);
        tmp$ret$0 = Math.sqrt(tmp0_sqrt);
        return this.ComplexFromPolar(tmp$ret$0, this.angle(c) / 2);
      };
      Companion_8.prototype.abs = function(c) {
        var tmp$ret$0;
        var tmp0_sqrt = c.real_1 * c.real_1 + c.imag_1 * c.imag_1;
        tmp$ret$0 = Math.sqrt(tmp0_sqrt);
        return tmp$ret$0;
      };
      Companion_8.prototype.angle = function(c) {
        var tmp$ret$0;
        var tmp0_atan2 = c.imag_1;
        var tmp1_atan2 = c.real_1;
        tmp$ret$0 = Math.atan2(tmp0_atan2, tmp1_atan2);
        return tmp$ret$0;
      };
      Companion_8.prototype.exp = function(c) {
        var tmp$ret$0;
        var tmp0_exp = c.real_1;
        tmp$ret$0 = Math.exp(tmp0_exp);
        var r = tmp$ret$0;
        var tmp$ret$1;
        var tmp1_cos = c.imag_1;
        tmp$ret$1 = Math.cos(tmp1_cos);
        var tmp = r * tmp$ret$1;
        var tmp$ret$2;
        var tmp2_sin = c.imag_1;
        tmp$ret$2 = Math.sin(tmp2_sin);
        return new Complex2(tmp, r * tmp$ret$2);
      };
      Companion_8.prototype.conjugate = function(c) {
        return new Complex2(c.real_1, -c.imag_1);
      };
      Companion_8.$metadata$ = objectMeta("Companion");
      var Companion_instance_8;
      function Companion_getInstance_8() {
        if (Companion_instance_8 == null)
          new Companion_8();
        return Companion_instance_8;
      }
      function Complex2(realpart, imagpart) {
        Companion_getInstance_8();
        this.real_1 = realpart;
        this.imag_1 = imagpart;
      }
      Complex2.prototype.real = function() {
        return this.real_1;
      };
      Complex2.prototype.imag = function() {
        return this.imag_1;
      };
      Complex2.prototype.abs = function() {
        return Companion_getInstance_8().abs(this);
      };
      Complex2.prototype.angle = function() {
        return Companion_getInstance_8().angle(this);
      };
      Complex2.prototype.timesComplex = function(c) {
        return Companion_getInstance_8().multiplyComplexComplex(this, c);
      };
      Complex2.prototype.timesReal = function(a) {
        return Companion_getInstance_8().multiplyComplexReal(this, a);
      };
      Complex2.prototype.conjugate = function() {
        return Companion_getInstance_8().conjugate(this);
      };
      Complex2.prototype.plusComplex = function(c) {
        return Companion_getInstance_8().addComplexComplex(this, c);
      };
      Complex2.prototype.plusReal = function(a) {
        return Companion_getInstance_8().addComplexReal(this, a);
      };
      Complex2.prototype.minusComplex = function(c) {
        return Companion_getInstance_8().subtractComplexComplex(this, c);
      };
      Complex2.prototype.minusReal = function(a) {
        return Companion_getInstance_8().subtractComplexReal(this, a);
      };
      Complex2.prototype.overReal = function(a) {
        return Companion_getInstance_8().divideComplexReal(this, a);
      };
      Complex2.prototype.overComplex = function(c) {
        return Companion_getInstance_8().divideComplexComplex(this, c);
      };
      Complex2.prototype.plusEqualsReal = function(a) {
        var tmp0_this = this;
        tmp0_this.real_1 = tmp0_this.real_1 + a;
      };
      Complex2.prototype.plusEqualsComplex = function(c) {
        var tmp0_this = this;
        tmp0_this.real_1 = tmp0_this.real_1 + c.real_1;
        var tmp1_this = this;
        tmp1_this.imag_1 = tmp1_this.imag_1 + c.imag_1;
      };
      Complex2.prototype.minusEqualsReal = function(a) {
        var tmp0_this = this;
        tmp0_this.real_1 = tmp0_this.real_1 - a;
      };
      Complex2.prototype.minusEqualsComplex = function(c) {
        var tmp0_this = this;
        tmp0_this.real_1 = tmp0_this.real_1 - c.real_1;
        var tmp1_this = this;
        tmp1_this.imag_1 = tmp1_this.imag_1 - c.imag_1;
      };
      Complex2.prototype.timesEqualsReal = function(a) {
        var tmp0_this = this;
        tmp0_this.real_1 = tmp0_this.real_1 * a;
        var tmp1_this = this;
        tmp1_this.imag_1 = tmp1_this.imag_1 * a;
      };
      Complex2.prototype.timesEqualsComplex = function(c) {
        var tmp = this.real_1 * c.real_1 - this.imag_1 * c.imag_1;
        this.imag_1 = this.real_1 * c.imag_1 + this.imag_1 * c.real_1;
        this.real_1 = tmp;
      };
      Complex2.prototype.divideEqualsReal = function(a) {
        var tmp0_this = this;
        tmp0_this.real_1 = tmp0_this.real_1 / a;
        var tmp1_this = this;
        tmp1_this.imag_1 = tmp1_this.imag_1 / a;
      };
      Complex2.prototype.divideEqualsComplex = function(c) {
        var scale = c.real_1 * c.real_1 + c.imag_1 * c.imag_1;
        var tmp = c.real_1 * this.real_1 + c.imag_1 * this.imag_1;
        this.imag_1 = c.real_1 * this.imag_1 - c.imag_1 * this.real_1;
        this.real_1 = tmp;
        this.divideEqualsReal(scale);
      };
      Complex2.prototype.toString = function() {
        return "" + this.real_1 + "  +  i * " + this.imag_1 + "\n";
      };
      Complex2.$metadata$ = classMeta("Complex");
      function warp($this, f, delta) {
        var tmp$ret$0;
        var tmp0_tan = get_PI() * f * delta;
        tmp$ret$0 = Math.tan(tmp0_tan);
        return tmp$ret$0;
      }
      function IIRFilter3(baseFilter, type, f1, f2, delta) {
        this.delta_1 = delta;
        this.f1__1 = f1;
        this.f2__1 = f2;
        var prototype;
        var tmp0_subject = type;
        var tmp0 = tmp0_subject.ordinal_1;
        switch (tmp0) {
          case 0:
            prototype = baseFilter.lptolp(warp(this, f2, delta));
            break;
          case 1:
            prototype = baseFilter.lptobp(warp(this, f1, delta), warp(this, f2, delta));
            break;
          case 2:
            prototype = baseFilter.lptohp(warp(this, f1, delta));
            break;
          default:
            throw IllegalStateException_init_$Create$("Undefined passband type");
        }
        var tn = new Float64Array(2);
        var td = new Float64Array(2);
        tn[0] = 1;
        tn[1] = -1;
        td[0] = 1;
        td[1] = 1;
        var S = Rational_ofArrays(tn, td);
        this.T_1 = Rational_ofConstant(1);
        this.sections_1 = ArrayList_init_$Create$();
        var inductionVariable = 0;
        var last = prototype.nSections() - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var R = prototype.getSection(i).mapRational(S);
            this.T_1.timesEqualsRational(R);
            var cn = R.numerator().coefficients();
            var cd = R.denominator().coefficients();
            var s2 = 1;
            if (!(cd[0] === 0))
              s2 = cd[0];
            var b0 = cn[0] / s2;
            var b1 = 0;
            if (cn.length >= 2)
              b1 = cn[1] / s2;
            var b2 = 0;
            if (cn.length >= 3)
              b2 = cn[2] / s2;
            var a1 = 0;
            if (cd.length >= 2)
              a1 = cd[1] / s2;
            var a2 = 0;
            if (cd.length >= 3)
              a2 = cd[2] / s2;
            this.sections_1.add_1j60pz_k$(new SecondOrderSection(b0, b1, b2, a1, a2));
          } while (!(i === last));
      }
      IIRFilter3.prototype.set_sections_7e6foy_k$ = function(_set____db54di) {
        this.sections_1 = _set____db54di;
      };
      IIRFilter3.prototype.get_sections_g4k5xl_k$ = function() {
        return this.sections_1;
      };
      IIRFilter3.prototype.set_T_dortqy_k$ = function(_set____db54di) {
        this.T_1 = _set____db54di;
      };
      IIRFilter3.prototype.get_T_1mhr57_k$ = function() {
        return this.T_1;
      };
      IIRFilter3.prototype.get_delta_iq7nnz_k$ = function() {
        return this.delta_1;
      };
      IIRFilter3.prototype.get_f1_knto18_k$ = function() {
        return this.f1__1;
      };
      IIRFilter3.prototype.get_f2_knto17_k$ = function() {
        return this.f2__1;
      };
      IIRFilter3.prototype.initialize = function() {
        var inductionVariable = 0;
        var last = this.sections_1.get_size_woubt6_k$() - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            this.sections_1.get_fkrdnv_k$(i).initialize_oabr29_k$();
          } while (inductionVariable <= last);
      };
      IIRFilter3.prototype.getDelta = function() {
        return this.delta_1;
      };
      IIRFilter3.prototype.getLowCorner = function() {
        return this.f1__1;
      };
      IIRFilter3.prototype.getHighCorner = function() {
        return this.f2__1;
      };
      IIRFilter3.prototype.filterNextSample = function(x2) {
        var retval = this.sections_1.get_fkrdnv_k$(0).filterSingle(x2);
        var inductionVariable = 1;
        var last = this.sections_1.get_size_woubt6_k$() - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            retval = this.sections_1.get_fkrdnv_k$(i).filterSingle(retval);
          } while (!(i === last));
        return retval;
      };
      IIRFilter3.prototype.filter = function(x2, y2) {
        var inductionVariable = 0;
        var last = y2.length - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            y2[i] = 0;
          } while (inductionVariable <= last);
        this.sections_1.get_fkrdnv_k$(0).filter(x2, y2);
        var inductionVariable_0 = 1;
        var last_0 = this.sections_1.get_size_woubt6_k$() - 1 | 0;
        if (inductionVariable_0 <= last_0)
          do {
            var i_0 = inductionVariable_0;
            inductionVariable_0 = inductionVariable_0 + 1 | 0;
            this.sections_1.get_fkrdnv_k$(i_0).filter(y2, y2);
          } while (!(i_0 === last_0));
      };
      IIRFilter3.prototype.filterInPlace = function(x2) {
        var tmp0_iterator = this.sections_1.iterator_jk1svi_k$();
        while (tmp0_iterator.hasNext_bitz1p_k$()) {
          var section = tmp0_iterator.next_20eer_k$();
          section.filter(x2, x2);
        }
      };
      IIRFilter3.prototype.evaluate = function(Omega) {
        var ejOmega = Companion_getInstance_8().exp(new Complex2(0, -Omega));
        return this.T_1.evaluateComplex(ejOmega);
      };
      IIRFilter3.prototype.groupDelay = function(Omega) {
        return this.T_1.discreteTimeGroupDelay(Omega);
      };
      IIRFilter3.prototype.toString = function() {
        var out = "IIR Filter:\n";
        var inductionVariable = 0;
        var last = this.sections_1.get_size_woubt6_k$() - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            out = out + ("\n  Section " + i + "\n");
            out = out + this.sections_1.get_fkrdnv_k$(i);
            out = out + new Char(_Char___init__impl__6a9atx(10));
          } while (inductionVariable <= last);
        return out;
      };
      IIRFilter3.$metadata$ = classMeta("IIRFilter");
      Object.defineProperty(IIRFilter3.prototype, "sections", {
        configurable: true,
        get: IIRFilter3.prototype.get_sections_g4k5xl_k$,
        set: IIRFilter3.prototype.set_sections_7e6foy_k$
      });
      Object.defineProperty(IIRFilter3.prototype, "T", {
        configurable: true,
        get: IIRFilter3.prototype.get_T_1mhr57_k$,
        set: IIRFilter3.prototype.set_T_dortqy_k$
      });
      Object.defineProperty(IIRFilter3.prototype, "delta", {
        configurable: true,
        get: IIRFilter3.prototype.get_delta_iq7nnz_k$
      });
      Object.defineProperty(IIRFilter3.prototype, "f1", {
        configurable: true,
        get: IIRFilter3.prototype.get_f1_knto18_k$
      });
      Object.defineProperty(IIRFilter3.prototype, "f2", {
        configurable: true,
        get: IIRFilter3.prototype.get_f2_knto17_k$
      });
      var PassbandType_LOWPASS_instance;
      var PassbandType_BANDPASS_instance;
      var PassbandType_HIGHPASS_instance;
      function values() {
        return [PassbandType_LOWPASS_getInstance(), PassbandType_BANDPASS_getInstance(), PassbandType_HIGHPASS_getInstance()];
      }
      function valueOf(value) {
        switch (value) {
          case "LOWPASS":
            return PassbandType_LOWPASS_getInstance();
          case "BANDPASS":
            return PassbandType_BANDPASS_getInstance();
          case "HIGHPASS":
            return PassbandType_HIGHPASS_getInstance();
          default:
            PassbandType_initEntries();
            THROW_ISE();
            break;
        }
      }
      var PassbandType_entriesInitialized;
      function PassbandType_initEntries() {
        if (PassbandType_entriesInitialized)
          return Unit_getInstance();
        PassbandType_entriesInitialized = true;
        PassbandType_LOWPASS_instance = new PassbandType2("LOWPASS", 0);
        PassbandType_BANDPASS_instance = new PassbandType2("BANDPASS", 1);
        PassbandType_HIGHPASS_instance = new PassbandType2("HIGHPASS", 2);
      }
      function PassbandType2(name, ordinal) {
        Enum.call(this, name, ordinal);
      }
      PassbandType2.$metadata$ = classMeta("PassbandType", void 0, void 0, void 0, void 0, Enum.prototype);
      Object.defineProperty(PassbandType2.prototype, "name", {
        configurable: true,
        get: PassbandType2.prototype.get_name_woqyms_k$
      });
      Object.defineProperty(PassbandType2.prototype, "ordinal", {
        configurable: true,
        get: PassbandType2.prototype.get_ordinal_ip24qg_k$
      });
      function PassbandType_LOWPASS_getInstance() {
        PassbandType_initEntries();
        return PassbandType_LOWPASS_instance;
      }
      function PassbandType_BANDPASS_getInstance() {
        PassbandType_initEntries();
        return PassbandType_BANDPASS_instance;
      }
      function PassbandType_HIGHPASS_getInstance() {
        PassbandType_initEntries();
        return PassbandType_HIGHPASS_instance;
      }
      function SecondOrderSection(b0, b1, b2, a1, a2) {
        this.b0__1 = b0;
        this.b1__1 = b1;
        this.b2__1 = b2;
        this.a1__1 = a1;
        this.a2__1 = a2;
        this.s1__1 = 0;
        this.s2__1 = 0;
        this.initialize_oabr29_k$();
      }
      SecondOrderSection.prototype.set_b0_6y8ao7_k$ = function(_set____db54di) {
        this.b0__1 = _set____db54di;
      };
      SecondOrderSection.prototype.get_b0_knto4p_k$ = function() {
        return this.b0__1;
      };
      SecondOrderSection.prototype.set_b1_15dfpi_k$ = function(_set____db54di) {
        this.b1__1 = _set____db54di;
      };
      SecondOrderSection.prototype.get_b1_knto4o_k$ = function() {
        return this.b1__1;
      };
      SecondOrderSection.prototype.set_b2_4nhf97_k$ = function(_set____db54di) {
        this.b2__1 = _set____db54di;
      };
      SecondOrderSection.prototype.get_b2_knto4n_k$ = function() {
        return this.b2__1;
      };
      SecondOrderSection.prototype.set_a1_w3e2cb_k$ = function(_set____db54di) {
        this.a1__1 = _set____db54di;
      };
      SecondOrderSection.prototype.get_a1_knto5j_k$ = function() {
        return this.a1__1;
      };
      SecondOrderSection.prototype.set_a2_x4v4o4_k$ = function(_set____db54di) {
        this.a2__1 = _set____db54di;
      };
      SecondOrderSection.prototype.get_a2_knto5i_k$ = function() {
        return this.a2__1;
      };
      SecondOrderSection.prototype.set_s1_1yjh8p_k$ = function(_set____db54di) {
        this.s1__1 = _set____db54di;
      };
      SecondOrderSection.prototype.get_s1_kntnq1_k$ = function() {
        return this.s1__1;
      };
      SecondOrderSection.prototype.set_s2_7rec7e_k$ = function(_set____db54di) {
        this.s2__1 = _set____db54di;
      };
      SecondOrderSection.prototype.get_s2_kntnq0_k$ = function() {
        return this.s2__1;
      };
      SecondOrderSection.prototype.initialize_oabr29_k$ = function() {
        this.s1__1 = 0;
        this.s2__1 = 0;
      };
      SecondOrderSection.prototype.filterSingle = function(x2) {
        var s0 = x2 - this.a1__1 * this.s1__1 - this.a2__1 * this.s2__1;
        var retval = this.b0__1 * s0 + this.b1__1 * this.s1__1 + this.b2__1 * this.s2__1;
        this.s2__1 = this.s1__1;
        this.s1__1 = s0;
        return retval;
      };
      SecondOrderSection.prototype.filter = function(x2, y2) {
        var s0;
        var tmp$ret$0;
        var tmp0_min = x2.length;
        var tmp1_min = y2.length;
        tmp$ret$0 = Math.min(tmp0_min, tmp1_min);
        var n2 = tmp$ret$0;
        var inductionVariable = 0;
        var last = n2 - 1 | 0;
        if (inductionVariable <= last)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            s0 = x2[i] - this.a1__1 * this.s1__1 - this.a2__1 * this.s2__1;
            y2[i] = this.b0__1 * s0 + this.b1__1 * this.s1__1 + this.b2__1 * this.s2__1;
            this.s2__1 = this.s1__1;
            this.s1__1 = s0;
          } while (!(i === last));
      };
      SecondOrderSection.prototype.toString = function() {
        var out = "  coefficients: \n";
        out = out + ("    b0: " + this.b0__1 + new Char(_Char___init__impl__6a9atx(10)));
        out = out + ("    b1: " + this.b1__1 + new Char(_Char___init__impl__6a9atx(10)));
        out = out + ("    b2: " + this.b2__1 + new Char(_Char___init__impl__6a9atx(10)));
        out = out + new Char(_Char___init__impl__6a9atx(10));
        out = out + ("    a1: " + this.a1__1 + new Char(_Char___init__impl__6a9atx(10)));
        out = out + ("    a2: " + this.a2__1 + new Char(_Char___init__impl__6a9atx(10)));
        out = out + "\n  states:  \n";
        out = out + ("    s1: " + this.s1__1 + new Char(_Char___init__impl__6a9atx(10)));
        out = out + ("    s2: " + this.s2__1 + new Char(_Char___init__impl__6a9atx(10)));
        return out;
      };
      SecondOrderSection.$metadata$ = classMeta("SecondOrderSection");
      function factorial($this, n2) {
        var retval = 1;
        if (n2 > 1) {
          var inductionVariable = 2;
          if (inductionVariable <= n2)
            do {
              var i = inductionVariable;
              inductionVariable = inductionVariable + 1 | 0;
              retval = imul(retval, i);
            } while (!(i === n2));
        }
        return retval;
      }
      function ThiranAllpass2(N, D) {
        Allpass2.call(this, N);
        var a = new Float64Array(N + 1 | 0);
        a[0] = 1;
        var inductionVariable = 1;
        if (inductionVariable <= N)
          do {
            var i = inductionVariable;
            inductionVariable = inductionVariable + 1 | 0;
            var prod = 1;
            var inductionVariable_0 = 0;
            if (inductionVariable_0 <= N)
              do {
                var n2 = inductionVariable_0;
                inductionVariable_0 = inductionVariable_0 + 1 | 0;
                prod = prod * ((D - N + n2) / (D - N + i + n2));
              } while (!(n2 === N));
            var tmp$ret$0;
            var tmp0_pow = i;
            tmp$ret$0 = Math.pow(-1, tmp0_pow);
            a[i] = tmp$ret$0 * (factorial(this, N) / imul(factorial(this, N - i | 0), factorial(this, i)) | 0) * prod;
          } while (!(i === N));
        var P = Polynomial_ofArray(a);
        this.k_1 = P.reflectionCoefficients();
        this.constructRationalRepresentation();
      }
      ThiranAllpass2.$metadata$ = classMeta("ThiranAllpass", void 0, void 0, void 0, void 0, Allpass2.prototype);
      function $jsExportAll$(_2) {
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        $com$oregondsp$signalProcessing.HammingWindow = HammingWindow2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        $com$oregondsp$signalProcessing.HanningWindow = HanningWindow2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        $com$oregondsp$signalProcessing.Sequence = Sequence2;
        $com$oregondsp$signalProcessing.Sequence.Sequence_fromArray = Sequence_fromArray;
        $com$oregondsp$signalProcessing.Sequence.Sequence_ofSize = Sequence_ofSize;
        Object.defineProperty($com$oregondsp$signalProcessing.Sequence, "Companion", {
          configurable: true,
          get: Companion_getInstance
        });
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        $com$oregondsp$signalProcessing.Window = Window2;
        $com$oregondsp$signalProcessing.Window.Window_fromArray = Window_fromArray;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$fft = $com$oregondsp$signalProcessing.fft || ($com$oregondsp$signalProcessing.fft = {});
        $com$oregondsp$signalProcessing$fft.CDFT = CDFT2;
        $com$oregondsp$signalProcessing$fft.CDFT.CDFT_ofLogSize = CDFT_ofLogSize;
        $com$oregondsp$signalProcessing$fft.CDFT.CDFT_ofArrays = CDFT_ofArrays;
        Object.defineProperty($com$oregondsp$signalProcessing$fft.CDFT, "Companion", {
          configurable: true,
          get: Companion_getInstance_0
        });
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$fft = $com$oregondsp$signalProcessing.fft || ($com$oregondsp$signalProcessing.fft = {});
        $com$oregondsp$signalProcessing$fft.RDFT = RDFT2;
        Object.defineProperty($com$oregondsp$signalProcessing$fft.RDFT, "Companion", {
          configurable: true,
          get: Companion_getInstance_4
        });
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        $com$oregondsp$signalProcessing$filter.LagrangePolynomial = LagrangePolynomial2;
        Object.defineProperty($com$oregondsp$signalProcessing$filter.LagrangePolynomial, "Companion", {
          configurable: true,
          get: Companion_getInstance_5
        });
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        $com$oregondsp$signalProcessing$filter.Polynomial = Polynomial2;
        $com$oregondsp$signalProcessing$filter.Polynomial.Polynomial_ofArray = Polynomial_ofArray;
        $com$oregondsp$signalProcessing$filter.Polynomial.Polynomial_ofPolynomial = Polynomial_ofPolynomial;
        $com$oregondsp$signalProcessing$filter.Polynomial.Polynomial_ofDegree = Polynomial_ofDegree;
        $com$oregondsp$signalProcessing$filter.Polynomial.Polynomial_ofConstant = Polynomial_ofConstant;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        $com$oregondsp$signalProcessing$filter.Rational = Rational2;
        $com$oregondsp$signalProcessing$filter.Rational.Rational_ofArrays = Rational_ofArrays;
        $com$oregondsp$signalProcessing$filter.Rational.Rational_ofPolynomials = Rational_ofPolynomials;
        $com$oregondsp$signalProcessing$filter.Rational.Rational_ofRational = Rational_ofRational;
        $com$oregondsp$signalProcessing$filter.Rational.Rational_ofConstant = Rational_ofConstant;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        $com$oregondsp$signalProcessing$filter$fir.ComplexAnalyticSignal = ComplexAnalyticSignal2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        $com$oregondsp$signalProcessing$filter$fir.Interpolator = Interpolator2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        $com$oregondsp$signalProcessing$filter$fir.OverlapAdd = OverlapAdd2;
        $com$oregondsp$signalProcessing$filter$fir.OverlapAdd.OverlapAdd_ofArray = OverlapAdd_ofArray;
        $com$oregondsp$signalProcessing$filter$fir.OverlapAdd.OverlapAdd_ofArrayOverlapAdd = OverlapAdd_ofArrayOverlapAdd;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.CenteredDifferentiator = CenteredDifferentiator2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.CenteredHilbertTransform = CenteredHilbertTransform2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.EquirippleBandpass = EquirippleBandpass2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.EquirippleFIRFilter = EquirippleFIRFilter2;
        Object.defineProperty($com$oregondsp$signalProcessing$filter$fir$equiripple.EquirippleFIRFilter, "Companion", {
          configurable: true,
          get: Companion_getInstance_7
        });
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.EquirippleHalfBand = EquirippleHalfBand2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.EquirippleHighpass = EquirippleHighpass2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.EquirippleLowpass = EquirippleLowpass2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.FIRTypeI = FIRTypeI2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.FIRTypeII = FIRTypeII2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.FIRTypeIII = FIRTypeIII2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.FIRTypeIV = FIRTypeIV;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.StaggeredDifferentiator = StaggeredDifferentiator2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$fir = $com$oregondsp$signalProcessing$filter.fir || ($com$oregondsp$signalProcessing$filter.fir = {});
        var $com$oregondsp$signalProcessing$filter$fir$equiripple = $com$oregondsp$signalProcessing$filter$fir.equiripple || ($com$oregondsp$signalProcessing$filter$fir.equiripple = {});
        $com$oregondsp$signalProcessing$filter$fir$equiripple.StaggeredHilbertTranform = StaggeredHilbertTranform2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$iir = $com$oregondsp$signalProcessing$filter.iir || ($com$oregondsp$signalProcessing$filter.iir = {});
        $com$oregondsp$signalProcessing$filter$iir.Allpass = Allpass2;
        $com$oregondsp$signalProcessing$filter$iir.Allpass.Allpass_ofPolynomial = Allpass_ofPolynomial;
        $com$oregondsp$signalProcessing$filter$iir.Allpass.Allpass_ofArray = Allpass_ofArray;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$iir = $com$oregondsp$signalProcessing$filter.iir || ($com$oregondsp$signalProcessing$filter.iir = {});
        $com$oregondsp$signalProcessing$filter$iir.AnalogPrototype = AnalogPrototype2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$iir = $com$oregondsp$signalProcessing$filter.iir || ($com$oregondsp$signalProcessing$filter.iir = {});
        $com$oregondsp$signalProcessing$filter$iir.Butterworth = Butterworth2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$iir = $com$oregondsp$signalProcessing$filter.iir || ($com$oregondsp$signalProcessing$filter.iir = {});
        $com$oregondsp$signalProcessing$filter$iir.ChebyshevI = ChebyshevI2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$iir = $com$oregondsp$signalProcessing$filter.iir || ($com$oregondsp$signalProcessing$filter.iir = {});
        $com$oregondsp$signalProcessing$filter$iir.ChebyshevII = ChebyshevII2;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$iir = $com$oregondsp$signalProcessing$filter.iir || ($com$oregondsp$signalProcessing$filter.iir = {});
        $com$oregondsp$signalProcessing$filter$iir.Complex = Complex2;
        $com$oregondsp$signalProcessing$filter$iir.Complex.Complex_fromReal = Complex_fromReal;
        Object.defineProperty($com$oregondsp$signalProcessing$filter$iir.Complex, "Companion", {
          configurable: true,
          get: Companion_getInstance_8
        });
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$iir = $com$oregondsp$signalProcessing$filter.iir || ($com$oregondsp$signalProcessing$filter.iir = {});
        $com$oregondsp$signalProcessing$filter$iir.IIRFilter = IIRFilter3;
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$iir = $com$oregondsp$signalProcessing$filter.iir || ($com$oregondsp$signalProcessing$filter.iir = {});
        $com$oregondsp$signalProcessing$filter$iir.PassbandType = PassbandType2;
        $com$oregondsp$signalProcessing$filter$iir.PassbandType.values = values;
        $com$oregondsp$signalProcessing$filter$iir.PassbandType.valueOf = valueOf;
        Object.defineProperty($com$oregondsp$signalProcessing$filter$iir.PassbandType, "LOWPASS", {
          configurable: true,
          get: PassbandType_LOWPASS_getInstance
        });
        Object.defineProperty($com$oregondsp$signalProcessing$filter$iir.PassbandType, "BANDPASS", {
          configurable: true,
          get: PassbandType_BANDPASS_getInstance
        });
        Object.defineProperty($com$oregondsp$signalProcessing$filter$iir.PassbandType, "HIGHPASS", {
          configurable: true,
          get: PassbandType_HIGHPASS_getInstance
        });
        var $com = _2.com || (_2.com = {});
        var $com$oregondsp = $com.oregondsp || ($com.oregondsp = {});
        var $com$oregondsp$signalProcessing = $com$oregondsp.signalProcessing || ($com$oregondsp.signalProcessing = {});
        var $com$oregondsp$signalProcessing$filter = $com$oregondsp$signalProcessing.filter || ($com$oregondsp$signalProcessing.filter = {});
        var $com$oregondsp$signalProcessing$filter$iir = $com$oregondsp$signalProcessing$filter.iir || ($com$oregondsp$signalProcessing$filter.iir = {});
        $com$oregondsp$signalProcessing$filter$iir.ThiranAllpass = ThiranAllpass2;
      }
      $jsExportAll$(_);
      return _;
    });
  }
});

// node_modules/handlebars/dist/cjs/handlebars/utils.js
var require_utils = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/utils.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.extend = extend3;
    exports.indexOf = indexOf;
    exports.escapeExpression = escapeExpression;
    exports.isEmpty = isEmpty;
    exports.createFrame = createFrame;
    exports.blockParams = blockParams;
    exports.appendContextPath = appendContextPath;
    var escape = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#x27;",
      "`": "&#x60;",
      "=": "&#x3D;"
    };
    var badChars = /[&<>"'`=]/g;
    var possible = /[&<>"'`=]/;
    function escapeChar(chr) {
      return escape[chr];
    }
    function extend3(obj) {
      for (var i = 1; i < arguments.length; i++) {
        for (var key in arguments[i]) {
          if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
            obj[key] = arguments[i][key];
          }
        }
      }
      return obj;
    }
    var toString = Object.prototype.toString;
    exports.toString = toString;
    var isFunction = function isFunction2(value) {
      return typeof value === "function";
    };
    if (isFunction(/x/)) {
      exports.isFunction = isFunction = function(value) {
        return typeof value === "function" && toString.call(value) === "[object Function]";
      };
    }
    exports.isFunction = isFunction;
    var isArray = Array.isArray || function(value) {
      return value && typeof value === "object" ? toString.call(value) === "[object Array]" : false;
    };
    exports.isArray = isArray;
    function indexOf(array3, value) {
      for (var i = 0, len = array3.length; i < len; i++) {
        if (array3[i] === value) {
          return i;
        }
      }
      return -1;
    }
    function escapeExpression(string4) {
      if (typeof string4 !== "string") {
        if (string4 && string4.toHTML) {
          return string4.toHTML();
        } else if (string4 == null) {
          return "";
        } else if (!string4) {
          return string4 + "";
        }
        string4 = "" + string4;
      }
      if (!possible.test(string4)) {
        return string4;
      }
      return string4.replace(badChars, escapeChar);
    }
    function isEmpty(value) {
      if (!value && value !== 0) {
        return true;
      } else if (isArray(value) && value.length === 0) {
        return true;
      } else {
        return false;
      }
    }
    function createFrame(object2) {
      var frame2 = extend3({}, object2);
      frame2._parent = object2;
      return frame2;
    }
    function blockParams(params, ids) {
      params.path = ids;
      return params;
    }
    function appendContextPath(contextPath, id2) {
      return (contextPath ? contextPath + "." : "") + id2;
    }
  }
});

// node_modules/handlebars/dist/cjs/handlebars/exception.js
var require_exception = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/exception.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    var errorProps = ["description", "fileName", "lineNumber", "endLineNumber", "message", "name", "number", "stack"];
    function Exception(message, node) {
      var loc = node && node.loc, line = void 0, endLineNumber = void 0, column = void 0, endColumn = void 0;
      if (loc) {
        line = loc.start.line;
        endLineNumber = loc.end.line;
        column = loc.start.column;
        endColumn = loc.end.column;
        message += " - " + line + ":" + column;
      }
      var tmp = Error.prototype.constructor.call(this, message);
      for (var idx = 0; idx < errorProps.length; idx++) {
        this[errorProps[idx]] = tmp[errorProps[idx]];
      }
      if (Error.captureStackTrace) {
        Error.captureStackTrace(this, Exception);
      }
      try {
        if (loc) {
          this.lineNumber = line;
          this.endLineNumber = endLineNumber;
          if (Object.defineProperty) {
            Object.defineProperty(this, "column", {
              value: column,
              enumerable: true
            });
            Object.defineProperty(this, "endColumn", {
              value: endColumn,
              enumerable: true
            });
          } else {
            this.column = column;
            this.endColumn = endColumn;
          }
        }
      } catch (nop) {
      }
    }
    Exception.prototype = new Error();
    exports["default"] = Exception;
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/helpers/block-helper-missing.js
var require_block_helper_missing = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/helpers/block-helper-missing.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    var _utils = require_utils();
    exports["default"] = function(instance) {
      instance.registerHelper("blockHelperMissing", function(context, options) {
        var inverse = options.inverse, fn = options.fn;
        if (context === true) {
          return fn(this);
        } else if (context === false || context == null) {
          return inverse(this);
        } else if (_utils.isArray(context)) {
          if (context.length > 0) {
            if (options.ids) {
              options.ids = [options.name];
            }
            return instance.helpers.each(context, options);
          } else {
            return inverse(this);
          }
        } else {
          if (options.data && options.ids) {
            var data = _utils.createFrame(options.data);
            data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
            options = { data };
          }
          return fn(context, options);
        }
      });
    };
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/helpers/each.js
var require_each = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/helpers/each.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _utils = require_utils();
    var _exception = require_exception();
    var _exception2 = _interopRequireDefault(_exception);
    exports["default"] = function(instance) {
      instance.registerHelper("each", function(context, options) {
        if (!options) {
          throw new _exception2["default"]("Must pass iterator to #each");
        }
        var fn = options.fn, inverse = options.inverse, i = 0, ret = "", data = void 0, contextPath = void 0;
        if (options.data && options.ids) {
          contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + ".";
        }
        if (_utils.isFunction(context)) {
          context = context.call(this);
        }
        if (options.data) {
          data = _utils.createFrame(options.data);
        }
        function execIteration(field, index, last) {
          if (data) {
            data.key = field;
            data.index = index;
            data.first = index === 0;
            data.last = !!last;
            if (contextPath) {
              data.contextPath = contextPath + field;
            }
          }
          ret = ret + fn(context[field], {
            data,
            blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
          });
        }
        if (context && typeof context === "object") {
          if (_utils.isArray(context)) {
            for (var j = context.length; i < j; i++) {
              if (i in context) {
                execIteration(i, i, i === context.length - 1);
              }
            }
          } else if (typeof Symbol === "function" && context[Symbol.iterator]) {
            var newContext = [];
            var iterator = context[Symbol.iterator]();
            for (var it = iterator.next(); !it.done; it = iterator.next()) {
              newContext.push(it.value);
            }
            context = newContext;
            for (var j = context.length; i < j; i++) {
              execIteration(i, i, i === context.length - 1);
            }
          } else {
            (function() {
              var priorKey = void 0;
              Object.keys(context).forEach(function(key) {
                if (priorKey !== void 0) {
                  execIteration(priorKey, i - 1);
                }
                priorKey = key;
                i++;
              });
              if (priorKey !== void 0) {
                execIteration(priorKey, i - 1, true);
              }
            })();
          }
        }
        if (i === 0) {
          ret = inverse(this);
        }
        return ret;
      });
    };
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/helpers/helper-missing.js
var require_helper_missing = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/helpers/helper-missing.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _exception = require_exception();
    var _exception2 = _interopRequireDefault(_exception);
    exports["default"] = function(instance) {
      instance.registerHelper("helperMissing", function() {
        if (arguments.length === 1) {
          return void 0;
        } else {
          throw new _exception2["default"]('Missing helper: "' + arguments[arguments.length - 1].name + '"');
        }
      });
    };
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/helpers/if.js
var require_if = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/helpers/if.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _utils = require_utils();
    var _exception = require_exception();
    var _exception2 = _interopRequireDefault(_exception);
    exports["default"] = function(instance) {
      instance.registerHelper("if", function(conditional, options) {
        if (arguments.length != 2) {
          throw new _exception2["default"]("#if requires exactly one argument");
        }
        if (_utils.isFunction(conditional)) {
          conditional = conditional.call(this);
        }
        if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
          return options.inverse(this);
        } else {
          return options.fn(this);
        }
      });
      instance.registerHelper("unless", function(conditional, options) {
        if (arguments.length != 2) {
          throw new _exception2["default"]("#unless requires exactly one argument");
        }
        return instance.helpers["if"].call(this, conditional, {
          fn: options.inverse,
          inverse: options.fn,
          hash: options.hash
        });
      });
    };
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/helpers/log.js
var require_log = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/helpers/log.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    exports["default"] = function(instance) {
      instance.registerHelper("log", function() {
        var args = [void 0], options = arguments[arguments.length - 1];
        for (var i = 0; i < arguments.length - 1; i++) {
          args.push(arguments[i]);
        }
        var level = 1;
        if (options.hash.level != null) {
          level = options.hash.level;
        } else if (options.data && options.data.level != null) {
          level = options.data.level;
        }
        args[0] = level;
        instance.log.apply(instance, args);
      });
    };
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/helpers/lookup.js
var require_lookup = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/helpers/lookup.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    exports["default"] = function(instance) {
      instance.registerHelper("lookup", function(obj, field, options) {
        if (!obj) {
          return obj;
        }
        return options.lookupProperty(obj, field);
      });
    };
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/helpers/with.js
var require_with = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/helpers/with.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _utils = require_utils();
    var _exception = require_exception();
    var _exception2 = _interopRequireDefault(_exception);
    exports["default"] = function(instance) {
      instance.registerHelper("with", function(context, options) {
        if (arguments.length != 2) {
          throw new _exception2["default"]("#with requires exactly one argument");
        }
        if (_utils.isFunction(context)) {
          context = context.call(this);
        }
        var fn = options.fn;
        if (!_utils.isEmpty(context)) {
          var data = options.data;
          if (options.data && options.ids) {
            data = _utils.createFrame(options.data);
            data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
          }
          return fn(context, {
            data,
            blockParams: _utils.blockParams([context], [data && data.contextPath])
          });
        } else {
          return options.inverse(this);
        }
      });
    };
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/helpers.js
var require_helpers = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/helpers.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.registerDefaultHelpers = registerDefaultHelpers;
    exports.moveHelperToHooks = moveHelperToHooks;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _helpersBlockHelperMissing = require_block_helper_missing();
    var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
    var _helpersEach = require_each();
    var _helpersEach2 = _interopRequireDefault(_helpersEach);
    var _helpersHelperMissing = require_helper_missing();
    var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
    var _helpersIf = require_if();
    var _helpersIf2 = _interopRequireDefault(_helpersIf);
    var _helpersLog = require_log();
    var _helpersLog2 = _interopRequireDefault(_helpersLog);
    var _helpersLookup = require_lookup();
    var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
    var _helpersWith = require_with();
    var _helpersWith2 = _interopRequireDefault(_helpersWith);
    function registerDefaultHelpers(instance) {
      _helpersBlockHelperMissing2["default"](instance);
      _helpersEach2["default"](instance);
      _helpersHelperMissing2["default"](instance);
      _helpersIf2["default"](instance);
      _helpersLog2["default"](instance);
      _helpersLookup2["default"](instance);
      _helpersWith2["default"](instance);
    }
    function moveHelperToHooks(instance, helperName, keepHelper) {
      if (instance.helpers[helperName]) {
        instance.hooks[helperName] = instance.helpers[helperName];
        if (!keepHelper) {
          instance.helpers[helperName] = void 0;
        }
      }
    }
  }
});

// node_modules/handlebars/dist/cjs/handlebars/decorators/inline.js
var require_inline = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/decorators/inline.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    var _utils = require_utils();
    exports["default"] = function(instance) {
      instance.registerDecorator("inline", function(fn, props, container, options) {
        var ret = fn;
        if (!props.partials) {
          props.partials = {};
          ret = function(context, options2) {
            var original = container.partials;
            container.partials = _utils.extend({}, original, props.partials);
            var ret2 = fn(context, options2);
            container.partials = original;
            return ret2;
          };
        }
        props.partials[options.args[0]] = options.fn;
        return ret;
      });
    };
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/decorators.js
var require_decorators = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/decorators.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.registerDefaultDecorators = registerDefaultDecorators;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _decoratorsInline = require_inline();
    var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
    function registerDefaultDecorators(instance) {
      _decoratorsInline2["default"](instance);
    }
  }
});

// node_modules/handlebars/dist/cjs/handlebars/logger.js
var require_logger = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/logger.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    var _utils = require_utils();
    var logger = {
      methodMap: ["debug", "info", "warn", "error"],
      level: "info",
      // Maps a given level value to the `methodMap` indexes above.
      lookupLevel: function lookupLevel(level) {
        if (typeof level === "string") {
          var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
          if (levelMap >= 0) {
            level = levelMap;
          } else {
            level = parseInt(level, 10);
          }
        }
        return level;
      },
      // Can be overridden in the host environment
      log: function log3(level) {
        level = logger.lookupLevel(level);
        if (typeof console !== "undefined" && logger.lookupLevel(logger.level) <= level) {
          var method = logger.methodMap[level];
          if (!console[method]) {
            method = "log";
          }
          for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            message[_key - 1] = arguments[_key];
          }
          console[method].apply(console, message);
        }
      }
    };
    exports["default"] = logger;
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/internal/proto-access.js
var require_proto_access = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/internal/proto-access.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.createProtoAccessControl = createProtoAccessControl;
    exports.resultIsAllowed = resultIsAllowed;
    exports.resetLoggedProperties = resetLoggedProperties;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _utils = require_utils();
    var _logger = require_logger();
    var _logger2 = _interopRequireDefault(_logger);
    var loggedProperties = /* @__PURE__ */ Object.create(null);
    function createProtoAccessControl(runtimeOptions) {
      var propertyWhiteList = /* @__PURE__ */ Object.create(null);
      propertyWhiteList["__proto__"] = false;
      _utils.extend(propertyWhiteList, runtimeOptions.allowedProtoProperties);
      var methodWhiteList = /* @__PURE__ */ Object.create(null);
      methodWhiteList["constructor"] = false;
      methodWhiteList["__defineGetter__"] = false;
      methodWhiteList["__defineSetter__"] = false;
      methodWhiteList["__lookupGetter__"] = false;
      methodWhiteList["__lookupSetter__"] = false;
      _utils.extend(methodWhiteList, runtimeOptions.allowedProtoMethods);
      return {
        properties: {
          whitelist: propertyWhiteList,
          defaultValue: runtimeOptions.allowProtoPropertiesByDefault
        },
        methods: {
          whitelist: methodWhiteList,
          defaultValue: runtimeOptions.allowProtoMethodsByDefault
        }
      };
    }
    function resultIsAllowed(result, protoAccessControl, propertyName) {
      if (typeof result === "function") {
        return checkWhiteList(protoAccessControl.methods, propertyName);
      } else {
        return checkWhiteList(protoAccessControl.properties, propertyName);
      }
    }
    function checkWhiteList(protoAccessControlForType, propertyName) {
      if (protoAccessControlForType.whitelist[propertyName] !== void 0) {
        return protoAccessControlForType.whitelist[propertyName] === true;
      }
      if (protoAccessControlForType.defaultValue !== void 0) {
        return protoAccessControlForType.defaultValue;
      }
      logUnexpecedPropertyAccessOnce(propertyName);
      return false;
    }
    function logUnexpecedPropertyAccessOnce(propertyName) {
      if (loggedProperties[propertyName] !== true) {
        loggedProperties[propertyName] = true;
        _logger2["default"].log("error", 'Handlebars: Access has been denied to resolve the property "' + propertyName + '" because it is not an "own property" of its parent.\nYou can add a runtime option to disable the check or this warning:\nSee https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details');
      }
    }
    function resetLoggedProperties() {
      Object.keys(loggedProperties).forEach(function(propertyName) {
        delete loggedProperties[propertyName];
      });
    }
  }
});

// node_modules/handlebars/dist/cjs/handlebars/base.js
var require_base = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/base.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.HandlebarsEnvironment = HandlebarsEnvironment;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _utils = require_utils();
    var _exception = require_exception();
    var _exception2 = _interopRequireDefault(_exception);
    var _helpers = require_helpers();
    var _decorators = require_decorators();
    var _logger = require_logger();
    var _logger2 = _interopRequireDefault(_logger);
    var _internalProtoAccess = require_proto_access();
    var VERSION2 = "4.7.9";
    exports.VERSION = VERSION2;
    var COMPILER_REVISION = 8;
    exports.COMPILER_REVISION = COMPILER_REVISION;
    var LAST_COMPATIBLE_COMPILER_REVISION = 7;
    exports.LAST_COMPATIBLE_COMPILER_REVISION = LAST_COMPATIBLE_COMPILER_REVISION;
    var REVISION_CHANGES = {
      1: "<= 1.0.rc.2",
      // 1.0.rc.2 is actually rev2 but doesn't report it
      2: "== 1.0.0-rc.3",
      3: "== 1.0.0-rc.4",
      4: "== 1.x.x",
      5: "== 2.0.0-alpha.x",
      6: ">= 2.0.0-beta.1",
      7: ">= 4.0.0 <4.3.0",
      8: ">= 4.3.0"
    };
    exports.REVISION_CHANGES = REVISION_CHANGES;
    var objectType = "[object Object]";
    function HandlebarsEnvironment(helpers, partials, decorators) {
      this.helpers = helpers || {};
      this.partials = partials || {};
      this.decorators = decorators || {};
      _helpers.registerDefaultHelpers(this);
      _decorators.registerDefaultDecorators(this);
    }
    HandlebarsEnvironment.prototype = {
      constructor: HandlebarsEnvironment,
      logger: _logger2["default"],
      log: _logger2["default"].log,
      registerHelper: function registerHelper(name, fn) {
        if (_utils.toString.call(name) === objectType) {
          if (fn) {
            throw new _exception2["default"]("Arg not supported with multiple helpers");
          }
          _utils.extend(this.helpers, name);
        } else {
          this.helpers[name] = fn;
        }
      },
      unregisterHelper: function unregisterHelper(name) {
        delete this.helpers[name];
      },
      registerPartial: function registerPartial(name, partial2) {
        if (_utils.toString.call(name) === objectType) {
          _utils.extend(this.partials, name);
        } else {
          if (typeof partial2 === "undefined") {
            throw new _exception2["default"]('Attempting to register a partial called "' + name + '" as undefined');
          }
          this.partials[name] = partial2;
        }
      },
      unregisterPartial: function unregisterPartial(name) {
        delete this.partials[name];
      },
      registerDecorator: function registerDecorator(name, fn) {
        if (_utils.toString.call(name) === objectType) {
          if (fn) {
            throw new _exception2["default"]("Arg not supported with multiple decorators");
          }
          _utils.extend(this.decorators, name);
        } else {
          this.decorators[name] = fn;
        }
      },
      unregisterDecorator: function unregisterDecorator(name) {
        delete this.decorators[name];
      },
      /**
       * Reset the memory of illegal property accesses that have already been logged.
       * @deprecated should only be used in handlebars test-cases
       */
      resetLoggedPropertyAccesses: function resetLoggedPropertyAccesses() {
        _internalProtoAccess.resetLoggedProperties();
      }
    };
    var log3 = _logger2["default"].log;
    exports.log = log3;
    exports.createFrame = _utils.createFrame;
    exports.logger = _logger2["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/safe-string.js
var require_safe_string = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/safe-string.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    function SafeString(string4) {
      this.string = string4;
    }
    SafeString.prototype.toString = SafeString.prototype.toHTML = function() {
      return "" + this.string;
    };
    exports["default"] = SafeString;
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/internal/wrapHelper.js
var require_wrapHelper = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/internal/wrapHelper.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.wrapHelper = wrapHelper;
    function wrapHelper(helper, transformOptionsFn) {
      if (typeof helper !== "function") {
        return helper;
      }
      var wrapper = function wrapper2() {
        var options = arguments[arguments.length - 1];
        arguments[arguments.length - 1] = transformOptionsFn(options);
        return helper.apply(this, arguments);
      };
      return wrapper;
    }
  }
});

// node_modules/handlebars/dist/cjs/handlebars/runtime.js
var require_runtime = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/runtime.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.checkRevision = checkRevision;
    exports.template = template;
    exports.wrapProgram = wrapProgram;
    exports.resolvePartial = resolvePartial;
    exports.invokePartial = invokePartial;
    exports.noop = noop2;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      } else {
        var newObj = {};
        if (obj != null) {
          for (var key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
          }
        }
        newObj["default"] = obj;
        return newObj;
      }
    }
    var _utils = require_utils();
    var Utils = _interopRequireWildcard(_utils);
    var _exception = require_exception();
    var _exception2 = _interopRequireDefault(_exception);
    var _base = require_base();
    var _helpers = require_helpers();
    var _internalWrapHelper = require_wrapHelper();
    var _internalProtoAccess = require_proto_access();
    function checkRevision(compilerInfo) {
      var compilerRevision = compilerInfo && compilerInfo[0] || 1, currentRevision = _base.COMPILER_REVISION;
      if (compilerRevision >= _base.LAST_COMPATIBLE_COMPILER_REVISION && compilerRevision <= _base.COMPILER_REVISION) {
        return;
      }
      if (compilerRevision < _base.LAST_COMPATIBLE_COMPILER_REVISION) {
        var runtimeVersions = _base.REVISION_CHANGES[currentRevision], compilerVersions = _base.REVISION_CHANGES[compilerRevision];
        throw new _exception2["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (" + runtimeVersions + ") or downgrade your runtime to an older version (" + compilerVersions + ").");
      } else {
        throw new _exception2["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version (" + compilerInfo[1] + ").");
      }
    }
    function template(templateSpec, env) {
      if (!env) {
        throw new _exception2["default"]("No environment passed to template");
      }
      if (!templateSpec || !templateSpec.main) {
        throw new _exception2["default"]("Unknown template object: " + typeof templateSpec);
      }
      templateSpec.main.decorator = templateSpec.main_d;
      env.VM.checkRevision(templateSpec.compiler);
      var templateWasPrecompiledWithCompilerV7 = templateSpec.compiler && templateSpec.compiler[0] === 7;
      function invokePartialWrapper(partial2, context, options) {
        if (options.hash) {
          context = Utils.extend({}, context, options.hash);
          if (options.ids) {
            options.ids[0] = true;
          }
        }
        partial2 = env.VM.resolvePartial.call(this, partial2, context, options);
        options.hooks = this.hooks;
        options.protoAccessControl = this.protoAccessControl;
        var result = env.VM.invokePartial.call(this, partial2, context, options);
        if (result == null && env.compile) {
          options.partials[options.name] = env.compile(partial2, templateSpec.compilerOptions, env);
          result = options.partials[options.name](context, options);
        }
        if (result != null) {
          if (options.indent) {
            var lines = result.split("\n");
            for (var i = 0, l2 = lines.length; i < l2; i++) {
              if (!lines[i] && i + 1 === l2) {
                break;
              }
              lines[i] = options.indent + lines[i];
            }
            result = lines.join("\n");
          }
          return result;
        } else {
          throw new _exception2["default"]("The partial " + options.name + " could not be compiled when running in runtime-only mode");
        }
      }
      var container = {
        strict: function strict(obj, name, loc) {
          if (!obj || !(name in obj)) {
            throw new _exception2["default"]('"' + name + '" not defined in ' + obj, {
              loc
            });
          }
          return container.lookupProperty(obj, name);
        },
        lookupProperty: function lookupProperty(parent, propertyName) {
          var result = parent[propertyName];
          if (result == null) {
            return result;
          }
          if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
            return result;
          }
          if (_internalProtoAccess.resultIsAllowed(result, container.protoAccessControl, propertyName)) {
            return result;
          }
          return void 0;
        },
        lookup: function lookup(depths, name) {
          var len = depths.length;
          for (var i = 0; i < len; i++) {
            var result = depths[i] && container.lookupProperty(depths[i], name);
            if (result != null) {
              return result;
            }
          }
        },
        lambda: function lambda(current, context) {
          return typeof current === "function" ? current.call(context) : current;
        },
        escapeExpression: Utils.escapeExpression,
        invokePartial: invokePartialWrapper,
        fn: function fn(i) {
          var ret2 = templateSpec[i];
          ret2.decorator = templateSpec[i + "_d"];
          return ret2;
        },
        programs: [],
        program: function program(i, data, declaredBlockParams, blockParams, depths) {
          var programWrapper = this.programs[i], fn = this.fn(i);
          if (data || depths || blockParams || declaredBlockParams) {
            programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
          } else if (!programWrapper) {
            programWrapper = this.programs[i] = wrapProgram(this, i, fn);
          }
          return programWrapper;
        },
        data: function data(value, depth) {
          while (value && depth--) {
            value = value._parent;
          }
          return value;
        },
        mergeIfNeeded: function mergeIfNeeded(param, common) {
          var obj = param || common;
          if (param && common && param !== common) {
            obj = Utils.extend({}, common, param);
          }
          return obj;
        },
        // An empty object to use as replacement for null-contexts
        nullContext: Object.seal({}),
        noop: env.VM.noop,
        compilerInfo: templateSpec.compiler
      };
      function ret(context) {
        var options = arguments.length <= 1 || arguments[1] === void 0 ? {} : arguments[1];
        var data = options.data;
        ret._setup(options);
        if (!options.partial && templateSpec.useData) {
          data = initData(context, data);
        }
        var depths = void 0, blockParams = templateSpec.useBlockParams ? [] : void 0;
        if (templateSpec.useDepths) {
          if (options.depths) {
            depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
          } else {
            depths = [context];
          }
        }
        function main(context2) {
          return "" + templateSpec.main(container, context2, container.helpers, container.partials, data, blockParams, depths);
        }
        main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
        return main(context, options);
      }
      ret.isTop = true;
      ret._setup = function(options) {
        if (!options.partial) {
          var mergedHelpers = {};
          addHelpers(mergedHelpers, env.helpers, container);
          addHelpers(mergedHelpers, options.helpers, container);
          container.helpers = mergedHelpers;
          if (templateSpec.usePartial) {
            container.partials = container.mergeIfNeeded(options.partials, env.partials);
          }
          if (templateSpec.usePartial || templateSpec.useDecorators) {
            container.decorators = Utils.extend({}, env.decorators, options.decorators);
          }
          container.hooks = {};
          container.protoAccessControl = _internalProtoAccess.createProtoAccessControl(options);
          var keepHelperInHelpers = options.allowCallsToHelperMissing || templateWasPrecompiledWithCompilerV7;
          _helpers.moveHelperToHooks(container, "helperMissing", keepHelperInHelpers);
          _helpers.moveHelperToHooks(container, "blockHelperMissing", keepHelperInHelpers);
        } else {
          container.protoAccessControl = options.protoAccessControl;
          container.helpers = options.helpers;
          container.partials = options.partials;
          container.decorators = options.decorators;
          container.hooks = options.hooks;
        }
      };
      ret._child = function(i, data, blockParams, depths) {
        if (templateSpec.useBlockParams && !blockParams) {
          throw new _exception2["default"]("must pass block params");
        }
        if (templateSpec.useDepths && !depths) {
          throw new _exception2["default"]("must pass parent depths");
        }
        return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
      };
      return ret;
    }
    function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
      function prog(context) {
        var options = arguments.length <= 1 || arguments[1] === void 0 ? {} : arguments[1];
        var currentDepths = depths;
        if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
          currentDepths = [context].concat(depths);
        }
        return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
      }
      prog = executeDecorators(fn, prog, container, depths, data, blockParams);
      prog.program = i;
      prog.depth = depths ? depths.length : 0;
      prog.blockParams = declaredBlockParams || 0;
      return prog;
    }
    function resolvePartial(partial2, context, options) {
      if (!partial2) {
        if (options.name === "@partial-block") {
          partial2 = lookupOwnProperty(options.data, "partial-block");
        } else {
          partial2 = lookupOwnProperty(options.partials, options.name);
        }
      } else if (!partial2.call && !options.name) {
        options.name = partial2;
        partial2 = lookupOwnProperty(options.partials, partial2);
      }
      return partial2;
    }
    function invokePartial(partial2, context, options) {
      var currentPartialBlock = lookupOwnProperty(options.data, "partial-block");
      options.partial = true;
      if (options.ids) {
        options.data.contextPath = options.ids[0] || options.data.contextPath;
      }
      var partialBlock = void 0;
      if (options.fn && options.fn !== noop2) {
        (function() {
          options.data = _base.createFrame(options.data);
          var fn = options.fn;
          partialBlock = options.data["partial-block"] = function partialBlockWrapper(context2) {
            var options2 = arguments.length <= 1 || arguments[1] === void 0 ? {} : arguments[1];
            options2.data = _base.createFrame(options2.data);
            options2.data["partial-block"] = currentPartialBlock;
            return fn(context2, options2);
          };
          if (fn.partials) {
            options.partials = Utils.extend({}, options.partials, fn.partials);
          }
        })();
      }
      if (partial2 === void 0 && partialBlock) {
        partial2 = partialBlock;
      }
      if (partial2 === void 0) {
        throw new _exception2["default"]("The partial " + options.name + " could not be found");
      } else if (partial2 instanceof Function) {
        return partial2(context, options);
      }
    }
    function noop2() {
      return "";
    }
    function lookupOwnProperty(obj, name) {
      if (obj && Object.prototype.hasOwnProperty.call(obj, name)) {
        return obj[name];
      }
    }
    function initData(context, data) {
      if (!data || !("root" in data)) {
        data = data ? _base.createFrame(data) : {};
        data.root = context;
      }
      return data;
    }
    function executeDecorators(fn, prog, container, depths, data, blockParams) {
      if (fn.decorator) {
        var props = {};
        prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
        Utils.extend(prog, props);
      }
      return prog;
    }
    function addHelpers(mergedHelpers, helpers, container) {
      if (!helpers) return;
      Object.keys(helpers).forEach(function(helperName) {
        var helper = helpers[helperName];
        mergedHelpers[helperName] = passLookupPropertyOption(helper, container);
      });
    }
    function passLookupPropertyOption(helper, container) {
      var lookupProperty = container.lookupProperty;
      return _internalWrapHelper.wrapHelper(helper, function(options) {
        options.lookupProperty = lookupProperty;
        return options;
      });
    }
  }
});

// node_modules/handlebars/dist/cjs/handlebars/no-conflict.js
var require_no_conflict = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/no-conflict.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    exports["default"] = function(Handlebars2) {
      (function() {
        if (typeof globalThis === "object") return;
        Object.prototype.__defineGetter__("__magic__", function() {
          return this;
        });
        __magic__.globalThis = __magic__;
        delete Object.prototype.__magic__;
      })();
      var $Handlebars = globalThis.Handlebars;
      Handlebars2.noConflict = function() {
        if (globalThis.Handlebars === Handlebars2) {
          globalThis.Handlebars = $Handlebars;
        }
        return Handlebars2;
      };
    };
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars.runtime.js
var require_handlebars_runtime = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars.runtime.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      } else {
        var newObj = {};
        if (obj != null) {
          for (var key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
          }
        }
        newObj["default"] = obj;
        return newObj;
      }
    }
    var _handlebarsBase = require_base();
    var base = _interopRequireWildcard(_handlebarsBase);
    var _handlebarsSafeString = require_safe_string();
    var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
    var _handlebarsException = require_exception();
    var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
    var _handlebarsUtils = require_utils();
    var Utils = _interopRequireWildcard(_handlebarsUtils);
    var _handlebarsRuntime = require_runtime();
    var runtime = _interopRequireWildcard(_handlebarsRuntime);
    var _handlebarsNoConflict = require_no_conflict();
    var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
    function create2() {
      var hb = new base.HandlebarsEnvironment();
      Utils.extend(hb, base);
      hb.SafeString = _handlebarsSafeString2["default"];
      hb.Exception = _handlebarsException2["default"];
      hb.Utils = Utils;
      hb.escapeExpression = Utils.escapeExpression;
      hb.VM = runtime;
      hb.template = function(spec) {
        return runtime.template(spec, hb);
      };
      return hb;
    }
    var inst = create2();
    inst.create = create2;
    _handlebarsNoConflict2["default"](inst);
    inst["default"] = inst;
    exports["default"] = inst;
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/compiler/ast.js
var require_ast = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/compiler/ast.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    var AST = {
      // Public API used to evaluate derived attributes regarding AST nodes
      helpers: {
        // a mustache is definitely a helper if:
        // * it is an eligible helper, and
        // * it has at least one parameter or hash segment
        helperExpression: function helperExpression(node) {
          return node.type === "SubExpression" || (node.type === "MustacheStatement" || node.type === "BlockStatement") && !!(node.params && node.params.length || node.hash);
        },
        scopedId: function scopedId(path2) {
          return /^\.|this\b/.test(path2.original);
        },
        // an ID is simple if it only has one part, and that part is not
        // `..` or `this`.
        simpleId: function simpleId(path2) {
          return path2.parts.length === 1 && !AST.helpers.scopedId(path2) && !path2.depth;
        }
      }
    };
    exports["default"] = AST;
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js
var require_parser = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    var handlebars = (function() {
      var parser = {
        trace: function trace() {
        },
        yy: {},
        symbols_: { "error": 2, "root": 3, "program": 4, "EOF": 5, "program_repetition0": 6, "statement": 7, "mustache": 8, "block": 9, "rawBlock": 10, "partial": 11, "partialBlock": 12, "content": 13, "COMMENT": 14, "CONTENT": 15, "openRawBlock": 16, "rawBlock_repetition0": 17, "END_RAW_BLOCK": 18, "OPEN_RAW_BLOCK": 19, "helperName": 20, "openRawBlock_repetition0": 21, "openRawBlock_option0": 22, "CLOSE_RAW_BLOCK": 23, "openBlock": 24, "block_option0": 25, "closeBlock": 26, "openInverse": 27, "block_option1": 28, "OPEN_BLOCK": 29, "openBlock_repetition0": 30, "openBlock_option0": 31, "openBlock_option1": 32, "CLOSE": 33, "OPEN_INVERSE": 34, "openInverse_repetition0": 35, "openInverse_option0": 36, "openInverse_option1": 37, "openInverseChain": 38, "OPEN_INVERSE_CHAIN": 39, "openInverseChain_repetition0": 40, "openInverseChain_option0": 41, "openInverseChain_option1": 42, "inverseAndProgram": 43, "INVERSE": 44, "inverseChain": 45, "inverseChain_option0": 46, "OPEN_ENDBLOCK": 47, "OPEN": 48, "mustache_repetition0": 49, "mustache_option0": 50, "OPEN_UNESCAPED": 51, "mustache_repetition1": 52, "mustache_option1": 53, "CLOSE_UNESCAPED": 54, "OPEN_PARTIAL": 55, "partialName": 56, "partial_repetition0": 57, "partial_option0": 58, "openPartialBlock": 59, "OPEN_PARTIAL_BLOCK": 60, "openPartialBlock_repetition0": 61, "openPartialBlock_option0": 62, "param": 63, "sexpr": 64, "OPEN_SEXPR": 65, "sexpr_repetition0": 66, "sexpr_option0": 67, "CLOSE_SEXPR": 68, "hash": 69, "hash_repetition_plus0": 70, "hashSegment": 71, "ID": 72, "EQUALS": 73, "blockParams": 74, "OPEN_BLOCK_PARAMS": 75, "blockParams_repetition_plus0": 76, "CLOSE_BLOCK_PARAMS": 77, "path": 78, "dataName": 79, "STRING": 80, "NUMBER": 81, "BOOLEAN": 82, "UNDEFINED": 83, "NULL": 84, "DATA": 85, "pathSegments": 86, "SEP": 87, "$accept": 0, "$end": 1 },
        terminals_: { 2: "error", 5: "EOF", 14: "COMMENT", 15: "CONTENT", 18: "END_RAW_BLOCK", 19: "OPEN_RAW_BLOCK", 23: "CLOSE_RAW_BLOCK", 29: "OPEN_BLOCK", 33: "CLOSE", 34: "OPEN_INVERSE", 39: "OPEN_INVERSE_CHAIN", 44: "INVERSE", 47: "OPEN_ENDBLOCK", 48: "OPEN", 51: "OPEN_UNESCAPED", 54: "CLOSE_UNESCAPED", 55: "OPEN_PARTIAL", 60: "OPEN_PARTIAL_BLOCK", 65: "OPEN_SEXPR", 68: "CLOSE_SEXPR", 72: "ID", 73: "EQUALS", 75: "OPEN_BLOCK_PARAMS", 77: "CLOSE_BLOCK_PARAMS", 80: "STRING", 81: "NUMBER", 82: "BOOLEAN", 83: "UNDEFINED", 84: "NULL", 85: "DATA", 87: "SEP" },
        productions_: [0, [3, 2], [4, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [13, 1], [10, 3], [16, 5], [9, 4], [9, 4], [24, 6], [27, 6], [38, 6], [43, 2], [45, 3], [45, 1], [26, 3], [8, 5], [8, 5], [11, 5], [12, 3], [59, 5], [63, 1], [63, 1], [64, 5], [69, 1], [71, 3], [74, 3], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [56, 1], [56, 1], [79, 2], [78, 1], [86, 3], [86, 1], [6, 0], [6, 2], [17, 0], [17, 2], [21, 0], [21, 2], [22, 0], [22, 1], [25, 0], [25, 1], [28, 0], [28, 1], [30, 0], [30, 2], [31, 0], [31, 1], [32, 0], [32, 1], [35, 0], [35, 2], [36, 0], [36, 1], [37, 0], [37, 1], [40, 0], [40, 2], [41, 0], [41, 1], [42, 0], [42, 1], [46, 0], [46, 1], [49, 0], [49, 2], [50, 0], [50, 1], [52, 0], [52, 2], [53, 0], [53, 1], [57, 0], [57, 2], [58, 0], [58, 1], [61, 0], [61, 2], [62, 0], [62, 1], [66, 0], [66, 2], [67, 0], [67, 1], [70, 1], [70, 2], [76, 1], [76, 2]],
        performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {
          var $0 = $$.length - 1;
          switch (yystate) {
            case 1:
              return $$[$0 - 1];
              break;
            case 2:
              this.$ = yy.prepareProgram($$[$0]);
              break;
            case 3:
              this.$ = $$[$0];
              break;
            case 4:
              this.$ = $$[$0];
              break;
            case 5:
              this.$ = $$[$0];
              break;
            case 6:
              this.$ = $$[$0];
              break;
            case 7:
              this.$ = $$[$0];
              break;
            case 8:
              this.$ = $$[$0];
              break;
            case 9:
              this.$ = {
                type: "CommentStatement",
                value: yy.stripComment($$[$0]),
                strip: yy.stripFlags($$[$0], $$[$0]),
                loc: yy.locInfo(this._$)
              };
              break;
            case 10:
              this.$ = {
                type: "ContentStatement",
                original: $$[$0],
                value: $$[$0],
                loc: yy.locInfo(this._$)
              };
              break;
            case 11:
              this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
              break;
            case 12:
              this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
              break;
            case 13:
              this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
              break;
            case 14:
              this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
              break;
            case 15:
              this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
              break;
            case 16:
              this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
              break;
            case 17:
              this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
              break;
            case 18:
              this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
              break;
            case 19:
              var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$), program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
              program.chained = true;
              this.$ = { strip: $$[$0 - 2].strip, program, chain: true };
              break;
            case 20:
              this.$ = $$[$0];
              break;
            case 21:
              this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
              break;
            case 22:
              this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
              break;
            case 23:
              this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
              break;
            case 24:
              this.$ = {
                type: "PartialStatement",
                name: $$[$0 - 3],
                params: $$[$0 - 2],
                hash: $$[$0 - 1],
                indent: "",
                strip: yy.stripFlags($$[$0 - 4], $$[$0]),
                loc: yy.locInfo(this._$)
              };
              break;
            case 25:
              this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
              break;
            case 26:
              this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
              break;
            case 27:
              this.$ = $$[$0];
              break;
            case 28:
              this.$ = $$[$0];
              break;
            case 29:
              this.$ = {
                type: "SubExpression",
                path: $$[$0 - 3],
                params: $$[$0 - 2],
                hash: $$[$0 - 1],
                loc: yy.locInfo(this._$)
              };
              break;
            case 30:
              this.$ = { type: "Hash", pairs: $$[$0], loc: yy.locInfo(this._$) };
              break;
            case 31:
              this.$ = { type: "HashPair", key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
              break;
            case 32:
              this.$ = yy.id($$[$0 - 1]);
              break;
            case 33:
              this.$ = $$[$0];
              break;
            case 34:
              this.$ = $$[$0];
              break;
            case 35:
              this.$ = { type: "StringLiteral", value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
              break;
            case 36:
              this.$ = { type: "NumberLiteral", value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
              break;
            case 37:
              this.$ = { type: "BooleanLiteral", value: $$[$0] === "true", original: $$[$0] === "true", loc: yy.locInfo(this._$) };
              break;
            case 38:
              this.$ = { type: "UndefinedLiteral", original: void 0, value: void 0, loc: yy.locInfo(this._$) };
              break;
            case 39:
              this.$ = { type: "NullLiteral", original: null, value: null, loc: yy.locInfo(this._$) };
              break;
            case 40:
              this.$ = $$[$0];
              break;
            case 41:
              this.$ = $$[$0];
              break;
            case 42:
              this.$ = yy.preparePath(true, $$[$0], this._$);
              break;
            case 43:
              this.$ = yy.preparePath(false, $$[$0], this._$);
              break;
            case 44:
              $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });
              this.$ = $$[$0 - 2];
              break;
            case 45:
              this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
              break;
            case 46:
              this.$ = [];
              break;
            case 47:
              $$[$0 - 1].push($$[$0]);
              break;
            case 48:
              this.$ = [];
              break;
            case 49:
              $$[$0 - 1].push($$[$0]);
              break;
            case 50:
              this.$ = [];
              break;
            case 51:
              $$[$0 - 1].push($$[$0]);
              break;
            case 58:
              this.$ = [];
              break;
            case 59:
              $$[$0 - 1].push($$[$0]);
              break;
            case 64:
              this.$ = [];
              break;
            case 65:
              $$[$0 - 1].push($$[$0]);
              break;
            case 70:
              this.$ = [];
              break;
            case 71:
              $$[$0 - 1].push($$[$0]);
              break;
            case 78:
              this.$ = [];
              break;
            case 79:
              $$[$0 - 1].push($$[$0]);
              break;
            case 82:
              this.$ = [];
              break;
            case 83:
              $$[$0 - 1].push($$[$0]);
              break;
            case 86:
              this.$ = [];
              break;
            case 87:
              $$[$0 - 1].push($$[$0]);
              break;
            case 90:
              this.$ = [];
              break;
            case 91:
              $$[$0 - 1].push($$[$0]);
              break;
            case 94:
              this.$ = [];
              break;
            case 95:
              $$[$0 - 1].push($$[$0]);
              break;
            case 98:
              this.$ = [$$[$0]];
              break;
            case 99:
              $$[$0 - 1].push($$[$0]);
              break;
            case 100:
              this.$ = [$$[$0]];
              break;
            case 101:
              $$[$0 - 1].push($$[$0]);
              break;
          }
        },
        table: [{ 3: 1, 4: 2, 5: [2, 46], 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: [1, 12], 15: [1, 20], 16: 17, 19: [1, 23], 24: 15, 27: 16, 29: [1, 21], 34: [1, 22], 39: [2, 2], 44: [2, 2], 47: [2, 2], 48: [1, 13], 51: [1, 14], 55: [1, 18], 59: 19, 60: [1, 24] }, { 1: [2, 1] }, { 5: [2, 47], 14: [2, 47], 15: [2, 47], 19: [2, 47], 29: [2, 47], 34: [2, 47], 39: [2, 47], 44: [2, 47], 47: [2, 47], 48: [2, 47], 51: [2, 47], 55: [2, 47], 60: [2, 47] }, { 5: [2, 3], 14: [2, 3], 15: [2, 3], 19: [2, 3], 29: [2, 3], 34: [2, 3], 39: [2, 3], 44: [2, 3], 47: [2, 3], 48: [2, 3], 51: [2, 3], 55: [2, 3], 60: [2, 3] }, { 5: [2, 4], 14: [2, 4], 15: [2, 4], 19: [2, 4], 29: [2, 4], 34: [2, 4], 39: [2, 4], 44: [2, 4], 47: [2, 4], 48: [2, 4], 51: [2, 4], 55: [2, 4], 60: [2, 4] }, { 5: [2, 5], 14: [2, 5], 15: [2, 5], 19: [2, 5], 29: [2, 5], 34: [2, 5], 39: [2, 5], 44: [2, 5], 47: [2, 5], 48: [2, 5], 51: [2, 5], 55: [2, 5], 60: [2, 5] }, { 5: [2, 6], 14: [2, 6], 15: [2, 6], 19: [2, 6], 29: [2, 6], 34: [2, 6], 39: [2, 6], 44: [2, 6], 47: [2, 6], 48: [2, 6], 51: [2, 6], 55: [2, 6], 60: [2, 6] }, { 5: [2, 7], 14: [2, 7], 15: [2, 7], 19: [2, 7], 29: [2, 7], 34: [2, 7], 39: [2, 7], 44: [2, 7], 47: [2, 7], 48: [2, 7], 51: [2, 7], 55: [2, 7], 60: [2, 7] }, { 5: [2, 8], 14: [2, 8], 15: [2, 8], 19: [2, 8], 29: [2, 8], 34: [2, 8], 39: [2, 8], 44: [2, 8], 47: [2, 8], 48: [2, 8], 51: [2, 8], 55: [2, 8], 60: [2, 8] }, { 5: [2, 9], 14: [2, 9], 15: [2, 9], 19: [2, 9], 29: [2, 9], 34: [2, 9], 39: [2, 9], 44: [2, 9], 47: [2, 9], 48: [2, 9], 51: [2, 9], 55: [2, 9], 60: [2, 9] }, { 20: 25, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 36, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 37, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 4: 38, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 15: [2, 48], 17: 39, 18: [2, 48] }, { 20: 41, 56: 40, 64: 42, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 44, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 5: [2, 10], 14: [2, 10], 15: [2, 10], 18: [2, 10], 19: [2, 10], 29: [2, 10], 34: [2, 10], 39: [2, 10], 44: [2, 10], 47: [2, 10], 48: [2, 10], 51: [2, 10], 55: [2, 10], 60: [2, 10] }, { 20: 45, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 46, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 47, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 41, 56: 48, 64: 42, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [2, 78], 49: 49, 65: [2, 78], 72: [2, 78], 80: [2, 78], 81: [2, 78], 82: [2, 78], 83: [2, 78], 84: [2, 78], 85: [2, 78] }, { 23: [2, 33], 33: [2, 33], 54: [2, 33], 65: [2, 33], 68: [2, 33], 72: [2, 33], 75: [2, 33], 80: [2, 33], 81: [2, 33], 82: [2, 33], 83: [2, 33], 84: [2, 33], 85: [2, 33] }, { 23: [2, 34], 33: [2, 34], 54: [2, 34], 65: [2, 34], 68: [2, 34], 72: [2, 34], 75: [2, 34], 80: [2, 34], 81: [2, 34], 82: [2, 34], 83: [2, 34], 84: [2, 34], 85: [2, 34] }, { 23: [2, 35], 33: [2, 35], 54: [2, 35], 65: [2, 35], 68: [2, 35], 72: [2, 35], 75: [2, 35], 80: [2, 35], 81: [2, 35], 82: [2, 35], 83: [2, 35], 84: [2, 35], 85: [2, 35] }, { 23: [2, 36], 33: [2, 36], 54: [2, 36], 65: [2, 36], 68: [2, 36], 72: [2, 36], 75: [2, 36], 80: [2, 36], 81: [2, 36], 82: [2, 36], 83: [2, 36], 84: [2, 36], 85: [2, 36] }, { 23: [2, 37], 33: [2, 37], 54: [2, 37], 65: [2, 37], 68: [2, 37], 72: [2, 37], 75: [2, 37], 80: [2, 37], 81: [2, 37], 82: [2, 37], 83: [2, 37], 84: [2, 37], 85: [2, 37] }, { 23: [2, 38], 33: [2, 38], 54: [2, 38], 65: [2, 38], 68: [2, 38], 72: [2, 38], 75: [2, 38], 80: [2, 38], 81: [2, 38], 82: [2, 38], 83: [2, 38], 84: [2, 38], 85: [2, 38] }, { 23: [2, 39], 33: [2, 39], 54: [2, 39], 65: [2, 39], 68: [2, 39], 72: [2, 39], 75: [2, 39], 80: [2, 39], 81: [2, 39], 82: [2, 39], 83: [2, 39], 84: [2, 39], 85: [2, 39] }, { 23: [2, 43], 33: [2, 43], 54: [2, 43], 65: [2, 43], 68: [2, 43], 72: [2, 43], 75: [2, 43], 80: [2, 43], 81: [2, 43], 82: [2, 43], 83: [2, 43], 84: [2, 43], 85: [2, 43], 87: [1, 50] }, { 72: [1, 35], 86: 51 }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 52: 52, 54: [2, 82], 65: [2, 82], 72: [2, 82], 80: [2, 82], 81: [2, 82], 82: [2, 82], 83: [2, 82], 84: [2, 82], 85: [2, 82] }, { 25: 53, 38: 55, 39: [1, 57], 43: 56, 44: [1, 58], 45: 54, 47: [2, 54] }, { 28: 59, 43: 60, 44: [1, 58], 47: [2, 56] }, { 13: 62, 15: [1, 20], 18: [1, 61] }, { 33: [2, 86], 57: 63, 65: [2, 86], 72: [2, 86], 80: [2, 86], 81: [2, 86], 82: [2, 86], 83: [2, 86], 84: [2, 86], 85: [2, 86] }, { 33: [2, 40], 65: [2, 40], 72: [2, 40], 80: [2, 40], 81: [2, 40], 82: [2, 40], 83: [2, 40], 84: [2, 40], 85: [2, 40] }, { 33: [2, 41], 65: [2, 41], 72: [2, 41], 80: [2, 41], 81: [2, 41], 82: [2, 41], 83: [2, 41], 84: [2, 41], 85: [2, 41] }, { 20: 64, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 65, 47: [1, 66] }, { 30: 67, 33: [2, 58], 65: [2, 58], 72: [2, 58], 75: [2, 58], 80: [2, 58], 81: [2, 58], 82: [2, 58], 83: [2, 58], 84: [2, 58], 85: [2, 58] }, { 33: [2, 64], 35: 68, 65: [2, 64], 72: [2, 64], 75: [2, 64], 80: [2, 64], 81: [2, 64], 82: [2, 64], 83: [2, 64], 84: [2, 64], 85: [2, 64] }, { 21: 69, 23: [2, 50], 65: [2, 50], 72: [2, 50], 80: [2, 50], 81: [2, 50], 82: [2, 50], 83: [2, 50], 84: [2, 50], 85: [2, 50] }, { 33: [2, 90], 61: 70, 65: [2, 90], 72: [2, 90], 80: [2, 90], 81: [2, 90], 82: [2, 90], 83: [2, 90], 84: [2, 90], 85: [2, 90] }, { 20: 74, 33: [2, 80], 50: 71, 63: 72, 64: 75, 65: [1, 43], 69: 73, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 72: [1, 79] }, { 23: [2, 42], 33: [2, 42], 54: [2, 42], 65: [2, 42], 68: [2, 42], 72: [2, 42], 75: [2, 42], 80: [2, 42], 81: [2, 42], 82: [2, 42], 83: [2, 42], 84: [2, 42], 85: [2, 42], 87: [1, 50] }, { 20: 74, 53: 80, 54: [2, 84], 63: 81, 64: 75, 65: [1, 43], 69: 82, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 83, 47: [1, 66] }, { 47: [2, 55] }, { 4: 84, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 47: [2, 20] }, { 20: 85, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 86, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 26: 87, 47: [1, 66] }, { 47: [2, 57] }, { 5: [2, 11], 14: [2, 11], 15: [2, 11], 19: [2, 11], 29: [2, 11], 34: [2, 11], 39: [2, 11], 44: [2, 11], 47: [2, 11], 48: [2, 11], 51: [2, 11], 55: [2, 11], 60: [2, 11] }, { 15: [2, 49], 18: [2, 49] }, { 20: 74, 33: [2, 88], 58: 88, 63: 89, 64: 75, 65: [1, 43], 69: 90, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 65: [2, 94], 66: 91, 68: [2, 94], 72: [2, 94], 80: [2, 94], 81: [2, 94], 82: [2, 94], 83: [2, 94], 84: [2, 94], 85: [2, 94] }, { 5: [2, 25], 14: [2, 25], 15: [2, 25], 19: [2, 25], 29: [2, 25], 34: [2, 25], 39: [2, 25], 44: [2, 25], 47: [2, 25], 48: [2, 25], 51: [2, 25], 55: [2, 25], 60: [2, 25] }, { 20: 92, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 31: 93, 33: [2, 60], 63: 94, 64: 75, 65: [1, 43], 69: 95, 70: 76, 71: 77, 72: [1, 78], 75: [2, 60], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 33: [2, 66], 36: 96, 63: 97, 64: 75, 65: [1, 43], 69: 98, 70: 76, 71: 77, 72: [1, 78], 75: [2, 66], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 22: 99, 23: [2, 52], 63: 100, 64: 75, 65: [1, 43], 69: 101, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 33: [2, 92], 62: 102, 63: 103, 64: 75, 65: [1, 43], 69: 104, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 105] }, { 33: [2, 79], 65: [2, 79], 72: [2, 79], 80: [2, 79], 81: [2, 79], 82: [2, 79], 83: [2, 79], 84: [2, 79], 85: [2, 79] }, { 33: [2, 81] }, { 23: [2, 27], 33: [2, 27], 54: [2, 27], 65: [2, 27], 68: [2, 27], 72: [2, 27], 75: [2, 27], 80: [2, 27], 81: [2, 27], 82: [2, 27], 83: [2, 27], 84: [2, 27], 85: [2, 27] }, { 23: [2, 28], 33: [2, 28], 54: [2, 28], 65: [2, 28], 68: [2, 28], 72: [2, 28], 75: [2, 28], 80: [2, 28], 81: [2, 28], 82: [2, 28], 83: [2, 28], 84: [2, 28], 85: [2, 28] }, { 23: [2, 30], 33: [2, 30], 54: [2, 30], 68: [2, 30], 71: 106, 72: [1, 107], 75: [2, 30] }, { 23: [2, 98], 33: [2, 98], 54: [2, 98], 68: [2, 98], 72: [2, 98], 75: [2, 98] }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 73: [1, 108], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 23: [2, 44], 33: [2, 44], 54: [2, 44], 65: [2, 44], 68: [2, 44], 72: [2, 44], 75: [2, 44], 80: [2, 44], 81: [2, 44], 82: [2, 44], 83: [2, 44], 84: [2, 44], 85: [2, 44], 87: [2, 44] }, { 54: [1, 109] }, { 54: [2, 83], 65: [2, 83], 72: [2, 83], 80: [2, 83], 81: [2, 83], 82: [2, 83], 83: [2, 83], 84: [2, 83], 85: [2, 83] }, { 54: [2, 85] }, { 5: [2, 13], 14: [2, 13], 15: [2, 13], 19: [2, 13], 29: [2, 13], 34: [2, 13], 39: [2, 13], 44: [2, 13], 47: [2, 13], 48: [2, 13], 51: [2, 13], 55: [2, 13], 60: [2, 13] }, { 38: 55, 39: [1, 57], 43: 56, 44: [1, 58], 45: 111, 46: 110, 47: [2, 76] }, { 33: [2, 70], 40: 112, 65: [2, 70], 72: [2, 70], 75: [2, 70], 80: [2, 70], 81: [2, 70], 82: [2, 70], 83: [2, 70], 84: [2, 70], 85: [2, 70] }, { 47: [2, 18] }, { 5: [2, 14], 14: [2, 14], 15: [2, 14], 19: [2, 14], 29: [2, 14], 34: [2, 14], 39: [2, 14], 44: [2, 14], 47: [2, 14], 48: [2, 14], 51: [2, 14], 55: [2, 14], 60: [2, 14] }, { 33: [1, 113] }, { 33: [2, 87], 65: [2, 87], 72: [2, 87], 80: [2, 87], 81: [2, 87], 82: [2, 87], 83: [2, 87], 84: [2, 87], 85: [2, 87] }, { 33: [2, 89] }, { 20: 74, 63: 115, 64: 75, 65: [1, 43], 67: 114, 68: [2, 96], 69: 116, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 117] }, { 32: 118, 33: [2, 62], 74: 119, 75: [1, 120] }, { 33: [2, 59], 65: [2, 59], 72: [2, 59], 75: [2, 59], 80: [2, 59], 81: [2, 59], 82: [2, 59], 83: [2, 59], 84: [2, 59], 85: [2, 59] }, { 33: [2, 61], 75: [2, 61] }, { 33: [2, 68], 37: 121, 74: 122, 75: [1, 120] }, { 33: [2, 65], 65: [2, 65], 72: [2, 65], 75: [2, 65], 80: [2, 65], 81: [2, 65], 82: [2, 65], 83: [2, 65], 84: [2, 65], 85: [2, 65] }, { 33: [2, 67], 75: [2, 67] }, { 23: [1, 123] }, { 23: [2, 51], 65: [2, 51], 72: [2, 51], 80: [2, 51], 81: [2, 51], 82: [2, 51], 83: [2, 51], 84: [2, 51], 85: [2, 51] }, { 23: [2, 53] }, { 33: [1, 124] }, { 33: [2, 91], 65: [2, 91], 72: [2, 91], 80: [2, 91], 81: [2, 91], 82: [2, 91], 83: [2, 91], 84: [2, 91], 85: [2, 91] }, { 33: [2, 93] }, { 5: [2, 22], 14: [2, 22], 15: [2, 22], 19: [2, 22], 29: [2, 22], 34: [2, 22], 39: [2, 22], 44: [2, 22], 47: [2, 22], 48: [2, 22], 51: [2, 22], 55: [2, 22], 60: [2, 22] }, { 23: [2, 99], 33: [2, 99], 54: [2, 99], 68: [2, 99], 72: [2, 99], 75: [2, 99] }, { 73: [1, 108] }, { 20: 74, 63: 125, 64: 75, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 23], 14: [2, 23], 15: [2, 23], 19: [2, 23], 29: [2, 23], 34: [2, 23], 39: [2, 23], 44: [2, 23], 47: [2, 23], 48: [2, 23], 51: [2, 23], 55: [2, 23], 60: [2, 23] }, { 47: [2, 19] }, { 47: [2, 77] }, { 20: 74, 33: [2, 72], 41: 126, 63: 127, 64: 75, 65: [1, 43], 69: 128, 70: 76, 71: 77, 72: [1, 78], 75: [2, 72], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 24], 14: [2, 24], 15: [2, 24], 19: [2, 24], 29: [2, 24], 34: [2, 24], 39: [2, 24], 44: [2, 24], 47: [2, 24], 48: [2, 24], 51: [2, 24], 55: [2, 24], 60: [2, 24] }, { 68: [1, 129] }, { 65: [2, 95], 68: [2, 95], 72: [2, 95], 80: [2, 95], 81: [2, 95], 82: [2, 95], 83: [2, 95], 84: [2, 95], 85: [2, 95] }, { 68: [2, 97] }, { 5: [2, 21], 14: [2, 21], 15: [2, 21], 19: [2, 21], 29: [2, 21], 34: [2, 21], 39: [2, 21], 44: [2, 21], 47: [2, 21], 48: [2, 21], 51: [2, 21], 55: [2, 21], 60: [2, 21] }, { 33: [1, 130] }, { 33: [2, 63] }, { 72: [1, 132], 76: 131 }, { 33: [1, 133] }, { 33: [2, 69] }, { 15: [2, 12], 18: [2, 12] }, { 14: [2, 26], 15: [2, 26], 19: [2, 26], 29: [2, 26], 34: [2, 26], 47: [2, 26], 48: [2, 26], 51: [2, 26], 55: [2, 26], 60: [2, 26] }, { 23: [2, 31], 33: [2, 31], 54: [2, 31], 68: [2, 31], 72: [2, 31], 75: [2, 31] }, { 33: [2, 74], 42: 134, 74: 135, 75: [1, 120] }, { 33: [2, 71], 65: [2, 71], 72: [2, 71], 75: [2, 71], 80: [2, 71], 81: [2, 71], 82: [2, 71], 83: [2, 71], 84: [2, 71], 85: [2, 71] }, { 33: [2, 73], 75: [2, 73] }, { 23: [2, 29], 33: [2, 29], 54: [2, 29], 65: [2, 29], 68: [2, 29], 72: [2, 29], 75: [2, 29], 80: [2, 29], 81: [2, 29], 82: [2, 29], 83: [2, 29], 84: [2, 29], 85: [2, 29] }, { 14: [2, 15], 15: [2, 15], 19: [2, 15], 29: [2, 15], 34: [2, 15], 39: [2, 15], 44: [2, 15], 47: [2, 15], 48: [2, 15], 51: [2, 15], 55: [2, 15], 60: [2, 15] }, { 72: [1, 137], 77: [1, 136] }, { 72: [2, 100], 77: [2, 100] }, { 14: [2, 16], 15: [2, 16], 19: [2, 16], 29: [2, 16], 34: [2, 16], 44: [2, 16], 47: [2, 16], 48: [2, 16], 51: [2, 16], 55: [2, 16], 60: [2, 16] }, { 33: [1, 138] }, { 33: [2, 75] }, { 33: [2, 32] }, { 72: [2, 101], 77: [2, 101] }, { 14: [2, 17], 15: [2, 17], 19: [2, 17], 29: [2, 17], 34: [2, 17], 39: [2, 17], 44: [2, 17], 47: [2, 17], 48: [2, 17], 51: [2, 17], 55: [2, 17], 60: [2, 17] }],
        defaultActions: { 4: [2, 1], 54: [2, 55], 56: [2, 20], 60: [2, 57], 73: [2, 81], 82: [2, 85], 86: [2, 18], 90: [2, 89], 101: [2, 53], 104: [2, 93], 110: [2, 19], 111: [2, 77], 116: [2, 97], 119: [2, 63], 122: [2, 69], 135: [2, 75], 136: [2, 32] },
        parseError: function parseError(str, hash2) {
          throw new Error(str);
        },
        parse: function parse5(input) {
          var self2 = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF2 = 1;
          this.lexer.setInput(input);
          this.lexer.yy = this.yy;
          this.yy.lexer = this.lexer;
          this.yy.parser = this;
          if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
          var yyloc = this.lexer.yylloc;
          lstack.push(yyloc);
          var ranges = this.lexer.options && this.lexer.options.ranges;
          if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
          function popStack(n2) {
            stack.length = stack.length - 2 * n2;
            vstack.length = vstack.length - n2;
            lstack.length = lstack.length - n2;
          }
          function lex() {
            var token;
            token = self2.lexer.lex() || 1;
            if (typeof token !== "number") {
              token = self2.symbols_[token] || token;
            }
            return token;
          }
          var symbol2, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;
          while (true) {
            state = stack[stack.length - 1];
            if (this.defaultActions[state]) {
              action = this.defaultActions[state];
            } else {
              if (symbol2 === null || typeof symbol2 == "undefined") {
                symbol2 = lex();
              }
              action = table[state] && table[state][symbol2];
            }
            if (typeof action === "undefined" || !action.length || !action[0]) {
              var errStr = "";
              if (!recovering) {
                expected = [];
                for (p in table[state]) if (this.terminals_[p] && p > 2) {
                  expected.push("'" + this.terminals_[p] + "'");
                }
                if (this.lexer.showPosition) {
                  errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol2] || symbol2) + "'";
                } else {
                  errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol2 == 1 ? "end of input" : "'" + (this.terminals_[symbol2] || symbol2) + "'");
                }
                this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol2] || symbol2, line: this.lexer.yylineno, loc: yyloc, expected });
              }
            }
            if (action[0] instanceof Array && action.length > 1) {
              throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol2);
            }
            switch (action[0]) {
              case 1:
                stack.push(symbol2);
                vstack.push(this.lexer.yytext);
                lstack.push(this.lexer.yylloc);
                stack.push(action[1]);
                symbol2 = null;
                if (!preErrorSymbol) {
                  yyleng = this.lexer.yyleng;
                  yytext = this.lexer.yytext;
                  yylineno = this.lexer.yylineno;
                  yyloc = this.lexer.yylloc;
                  if (recovering > 0) recovering--;
                } else {
                  symbol2 = preErrorSymbol;
                  preErrorSymbol = null;
                }
                break;
              case 2:
                len = this.productions_[action[1]][1];
                yyval.$ = vstack[vstack.length - len];
                yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column };
                if (ranges) {
                  yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
                }
                r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
                if (typeof r !== "undefined") {
                  return r;
                }
                if (len) {
                  stack = stack.slice(0, -1 * len * 2);
                  vstack = vstack.slice(0, -1 * len);
                  lstack = lstack.slice(0, -1 * len);
                }
                stack.push(this.productions_[action[1]][0]);
                vstack.push(yyval.$);
                lstack.push(yyval._$);
                newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
                stack.push(newState);
                break;
              case 3:
                return true;
            }
          }
          return true;
        }
      };
      var lexer = (function() {
        var lexer2 = {
          EOF: 1,
          parseError: function parseError(str, hash2) {
            if (this.yy.parser) {
              this.yy.parser.parseError(str, hash2);
            } else {
              throw new Error(str);
            }
          },
          setInput: function setInput(input) {
            this._input = input;
            this._more = this._less = this.done = false;
            this.yylineno = this.yyleng = 0;
            this.yytext = this.matched = this.match = "";
            this.conditionStack = ["INITIAL"];
            this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
            if (this.options.ranges) this.yylloc.range = [0, 0];
            this.offset = 0;
            return this;
          },
          input: function input() {
            var ch = this._input[0];
            this.yytext += ch;
            this.yyleng++;
            this.offset++;
            this.match += ch;
            this.matched += ch;
            var lines = ch.match(/(?:\r\n?|\n).*/g);
            if (lines) {
              this.yylineno++;
              this.yylloc.last_line++;
            } else {
              this.yylloc.last_column++;
            }
            if (this.options.ranges) this.yylloc.range[1]++;
            this._input = this._input.slice(1);
            return ch;
          },
          unput: function unput(ch) {
            var len = ch.length;
            var lines = ch.split(/(?:\r\n?|\n)/g);
            this._input = ch + this._input;
            this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
            this.offset -= len;
            var oldLines = this.match.split(/(?:\r\n?|\n)/g);
            this.match = this.match.substr(0, this.match.length - 1);
            this.matched = this.matched.substr(0, this.matched.length - 1);
            if (lines.length - 1) this.yylineno -= lines.length - 1;
            var r = this.yylloc.range;
            this.yylloc = {
              first_line: this.yylloc.first_line,
              last_line: this.yylineno + 1,
              first_column: this.yylloc.first_column,
              last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
            };
            if (this.options.ranges) {
              this.yylloc.range = [r[0], r[0] + this.yyleng - len];
            }
            return this;
          },
          more: function more() {
            this._more = true;
            return this;
          },
          less: function less(n2) {
            this.unput(this.match.slice(n2));
          },
          pastInput: function pastInput() {
            var past = this.matched.substr(0, this.matched.length - this.match.length);
            return (past.length > 20 ? "..." : "") + past.substr(-20).replace(/\n/g, "");
          },
          upcomingInput: function upcomingInput() {
            var next = this.match;
            if (next.length < 20) {
              next += this._input.substr(0, 20 - next.length);
            }
            return (next.substr(0, 20) + (next.length > 20 ? "..." : "")).replace(/\n/g, "");
          },
          showPosition: function showPosition() {
            var pre = this.pastInput();
            var c = new Array(pre.length + 1).join("-");
            return pre + this.upcomingInput() + "\n" + c + "^";
          },
          next: function next() {
            if (this.done) {
              return this.EOF;
            }
            if (!this._input) this.done = true;
            var token, match2, tempMatch, index, col, lines;
            if (!this._more) {
              this.yytext = "";
              this.match = "";
            }
            var rules = this._currentRules();
            for (var i = 0; i < rules.length; i++) {
              tempMatch = this._input.match(this.rules[rules[i]]);
              if (tempMatch && (!match2 || tempMatch[0].length > match2[0].length)) {
                match2 = tempMatch;
                index = i;
                if (!this.options.flex) break;
              }
            }
            if (match2) {
              lines = match2[0].match(/(?:\r\n?|\n).*/g);
              if (lines) this.yylineno += lines.length;
              this.yylloc = {
                first_line: this.yylloc.last_line,
                last_line: this.yylineno + 1,
                first_column: this.yylloc.last_column,
                last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match2[0].length
              };
              this.yytext += match2[0];
              this.match += match2[0];
              this.matches = match2;
              this.yyleng = this.yytext.length;
              if (this.options.ranges) {
                this.yylloc.range = [this.offset, this.offset += this.yyleng];
              }
              this._more = false;
              this._input = this._input.slice(match2[0].length);
              this.matched += match2[0];
              token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
              if (this.done && this._input) this.done = false;
              if (token) return token;
              else return;
            }
            if (this._input === "") {
              return this.EOF;
            } else {
              return this.parseError("Lexical error on line " + (this.yylineno + 1) + ". Unrecognized text.\n" + this.showPosition(), { text: "", token: null, line: this.yylineno });
            }
          },
          lex: function lex() {
            var r = this.next();
            if (typeof r !== "undefined") {
              return r;
            } else {
              return this.lex();
            }
          },
          begin: function begin(condition) {
            this.conditionStack.push(condition);
          },
          popState: function popState() {
            return this.conditionStack.pop();
          },
          _currentRules: function _currentRules() {
            return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
          },
          topState: function topState() {
            return this.conditionStack[this.conditionStack.length - 2];
          },
          pushState: function begin(condition) {
            this.begin(condition);
          }
        };
        lexer2.options = {};
        lexer2.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {
          function strip(start2, end) {
            return yy_.yytext = yy_.yytext.substring(start2, yy_.yyleng - end + start2);
          }
          var YYSTATE = YY_START;
          switch ($avoiding_name_collisions) {
            case 0:
              if (yy_.yytext.slice(-2) === "\\\\") {
                strip(0, 1);
                this.begin("mu");
              } else if (yy_.yytext.slice(-1) === "\\") {
                strip(0, 1);
                this.begin("emu");
              } else {
                this.begin("mu");
              }
              if (yy_.yytext) return 15;
              break;
            case 1:
              return 15;
              break;
            case 2:
              this.popState();
              return 15;
              break;
            case 3:
              this.begin("raw");
              return 15;
              break;
            case 4:
              this.popState();
              if (this.conditionStack[this.conditionStack.length - 1] === "raw") {
                return 15;
              } else {
                strip(5, 9);
                return "END_RAW_BLOCK";
              }
              break;
            case 5:
              return 15;
              break;
            case 6:
              this.popState();
              return 14;
              break;
            case 7:
              return 65;
              break;
            case 8:
              return 68;
              break;
            case 9:
              return 19;
              break;
            case 10:
              this.popState();
              this.begin("raw");
              return 23;
              break;
            case 11:
              return 55;
              break;
            case 12:
              return 60;
              break;
            case 13:
              return 29;
              break;
            case 14:
              return 47;
              break;
            case 15:
              this.popState();
              return 44;
              break;
            case 16:
              this.popState();
              return 44;
              break;
            case 17:
              return 34;
              break;
            case 18:
              return 39;
              break;
            case 19:
              return 51;
              break;
            case 20:
              return 48;
              break;
            case 21:
              this.unput(yy_.yytext);
              this.popState();
              this.begin("com");
              break;
            case 22:
              this.popState();
              return 14;
              break;
            case 23:
              return 48;
              break;
            case 24:
              return 73;
              break;
            case 25:
              return 72;
              break;
            case 26:
              return 72;
              break;
            case 27:
              return 87;
              break;
            case 28:
              break;
            case 29:
              this.popState();
              return 54;
              break;
            case 30:
              this.popState();
              return 33;
              break;
            case 31:
              yy_.yytext = strip(1, 2).replace(/\\"/g, '"');
              return 80;
              break;
            case 32:
              yy_.yytext = strip(1, 2).replace(/\\'/g, "'");
              return 80;
              break;
            case 33:
              return 85;
              break;
            case 34:
              return 82;
              break;
            case 35:
              return 82;
              break;
            case 36:
              return 83;
              break;
            case 37:
              return 84;
              break;
            case 38:
              return 81;
              break;
            case 39:
              return 75;
              break;
            case 40:
              return 77;
              break;
            case 41:
              return 72;
              break;
            case 42:
              yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, "$1");
              return 72;
              break;
            case 43:
              return "INVALID";
              break;
            case 44:
              return 5;
              break;
          }
        };
        lexer2.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{(?=[^\/]))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]+?(?=(\{\{\{\{)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#>)/, /^(?:\{\{(~)?#\*?)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?\*?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
        lexer2.conditions = { "mu": { "rules": [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } };
        return lexer2;
      })();
      parser.lexer = lexer;
      function Parser() {
        this.yy = {};
      }
      Parser.prototype = parser;
      parser.Parser = Parser;
      return new Parser();
    })();
    exports["default"] = handlebars;
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/compiler/visitor.js
var require_visitor = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/compiler/visitor.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _exception = require_exception();
    var _exception2 = _interopRequireDefault(_exception);
    function Visitor() {
      this.parents = [];
    }
    Visitor.prototype = {
      constructor: Visitor,
      mutating: false,
      // Visits a given value. If mutating, will replace the value if necessary.
      acceptKey: function acceptKey(node, name) {
        var value = this.accept(node[name]);
        if (this.mutating) {
          if (value && !Visitor.prototype[value.type]) {
            throw new _exception2["default"]('Unexpected node type "' + value.type + '" found when accepting ' + name + " on " + node.type);
          }
          node[name] = value;
        }
      },
      // Performs an accept operation with added sanity check to ensure
      // required keys are not removed.
      acceptRequired: function acceptRequired(node, name) {
        this.acceptKey(node, name);
        if (!node[name]) {
          throw new _exception2["default"](node.type + " requires " + name);
        }
      },
      // Traverses a given array. If mutating, empty respnses will be removed
      // for child elements.
      acceptArray: function acceptArray(array3) {
        for (var i = 0, l2 = array3.length; i < l2; i++) {
          this.acceptKey(array3, i);
          if (!array3[i]) {
            array3.splice(i, 1);
            i--;
            l2--;
          }
        }
      },
      accept: function accept(object2) {
        if (!object2) {
          return;
        }
        if (!this[object2.type]) {
          throw new _exception2["default"]("Unknown type: " + object2.type, object2);
        }
        if (this.current) {
          this.parents.unshift(this.current);
        }
        this.current = object2;
        var ret = this[object2.type](object2);
        this.current = this.parents.shift();
        if (!this.mutating || ret) {
          return ret;
        } else if (ret !== false) {
          return object2;
        }
      },
      Program: function Program(program) {
        this.acceptArray(program.body);
      },
      MustacheStatement: visitSubExpression,
      Decorator: visitSubExpression,
      BlockStatement: visitBlock,
      DecoratorBlock: visitBlock,
      PartialStatement: visitPartial,
      PartialBlockStatement: function PartialBlockStatement(partial2) {
        visitPartial.call(this, partial2);
        this.acceptKey(partial2, "program");
      },
      ContentStatement: function ContentStatement() {
      },
      CommentStatement: function CommentStatement() {
      },
      SubExpression: visitSubExpression,
      PathExpression: function PathExpression() {
      },
      StringLiteral: function StringLiteral() {
      },
      NumberLiteral: function NumberLiteral() {
      },
      BooleanLiteral: function BooleanLiteral() {
      },
      UndefinedLiteral: function UndefinedLiteral() {
      },
      NullLiteral: function NullLiteral() {
      },
      Hash: function Hash(hash2) {
        this.acceptArray(hash2.pairs);
      },
      HashPair: function HashPair(pair) {
        this.acceptRequired(pair, "value");
      }
    };
    function visitSubExpression(mustache) {
      this.acceptRequired(mustache, "path");
      this.acceptArray(mustache.params);
      this.acceptKey(mustache, "hash");
    }
    function visitBlock(block) {
      visitSubExpression.call(this, block);
      this.acceptKey(block, "program");
      this.acceptKey(block, "inverse");
    }
    function visitPartial(partial2) {
      this.acceptRequired(partial2, "name");
      this.acceptArray(partial2.params);
      this.acceptKey(partial2, "hash");
    }
    exports["default"] = Visitor;
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/compiler/whitespace-control.js
var require_whitespace_control = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/compiler/whitespace-control.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _visitor = require_visitor();
    var _visitor2 = _interopRequireDefault(_visitor);
    function WhitespaceControl() {
      var options = arguments.length <= 0 || arguments[0] === void 0 ? {} : arguments[0];
      this.options = options;
    }
    WhitespaceControl.prototype = new _visitor2["default"]();
    WhitespaceControl.prototype.Program = function(program) {
      var doStandalone = !this.options.ignoreStandalone;
      var isRoot = !this.isRootSeen;
      this.isRootSeen = true;
      var body = program.body;
      for (var i = 0, l2 = body.length; i < l2; i++) {
        var current = body[i], strip = this.accept(current);
        if (!strip) {
          continue;
        }
        var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot), _isNextWhitespace = isNextWhitespace(body, i, isRoot), openStandalone = strip.openStandalone && _isPrevWhitespace, closeStandalone = strip.closeStandalone && _isNextWhitespace, inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
        if (strip.close) {
          omitRight(body, i, true);
        }
        if (strip.open) {
          omitLeft(body, i, true);
        }
        if (doStandalone && inlineStandalone) {
          omitRight(body, i);
          if (omitLeft(body, i)) {
            if (current.type === "PartialStatement") {
              current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
            }
          }
        }
        if (doStandalone && openStandalone) {
          omitRight((current.program || current.inverse).body);
          omitLeft(body, i);
        }
        if (doStandalone && closeStandalone) {
          omitRight(body, i);
          omitLeft((current.inverse || current.program).body);
        }
      }
      return program;
    };
    WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function(block) {
      this.accept(block.program);
      this.accept(block.inverse);
      var program = block.program || block.inverse, inverse = block.program && block.inverse, firstInverse = inverse, lastInverse = inverse;
      if (inverse && inverse.chained) {
        firstInverse = inverse.body[0].program;
        while (lastInverse.chained) {
          lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
        }
      }
      var strip = {
        open: block.openStrip.open,
        close: block.closeStrip.close,
        // Determine the standalone candiacy. Basically flag our content as being possibly standalone
        // so our parent can determine if we actually are standalone
        openStandalone: isNextWhitespace(program.body),
        closeStandalone: isPrevWhitespace((firstInverse || program).body)
      };
      if (block.openStrip.close) {
        omitRight(program.body, null, true);
      }
      if (inverse) {
        var inverseStrip = block.inverseStrip;
        if (inverseStrip.open) {
          omitLeft(program.body, null, true);
        }
        if (inverseStrip.close) {
          omitRight(firstInverse.body, null, true);
        }
        if (block.closeStrip.open) {
          omitLeft(lastInverse.body, null, true);
        }
        if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
          omitLeft(program.body);
          omitRight(firstInverse.body);
        }
      } else if (block.closeStrip.open) {
        omitLeft(program.body, null, true);
      }
      return strip;
    };
    WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function(mustache) {
      return mustache.strip;
    };
    WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function(node) {
      var strip = node.strip || {};
      return {
        inlineStandalone: true,
        open: strip.open,
        close: strip.close
      };
    };
    function isPrevWhitespace(body, i, isRoot) {
      if (i === void 0) {
        i = body.length;
      }
      var prev = body[i - 1], sibling = body[i - 2];
      if (!prev) {
        return isRoot;
      }
      if (prev.type === "ContentStatement") {
        return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
      }
    }
    function isNextWhitespace(body, i, isRoot) {
      if (i === void 0) {
        i = -1;
      }
      var next = body[i + 1], sibling = body[i + 2];
      if (!next) {
        return isRoot;
      }
      if (next.type === "ContentStatement") {
        return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
      }
    }
    function omitRight(body, i, multiple) {
      var current = body[i == null ? 0 : i + 1];
      if (!current || current.type !== "ContentStatement" || !multiple && current.rightStripped) {
        return;
      }
      var original = current.value;
      current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, "");
      current.rightStripped = current.value !== original;
    }
    function omitLeft(body, i, multiple) {
      var current = body[i == null ? body.length - 1 : i - 1];
      if (!current || current.type !== "ContentStatement" || !multiple && current.leftStripped) {
        return;
      }
      var original = current.value;
      current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, "");
      current.leftStripped = current.value !== original;
      return current.leftStripped;
    }
    exports["default"] = WhitespaceControl;
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/compiler/helpers.js
var require_helpers2 = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/compiler/helpers.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.SourceLocation = SourceLocation;
    exports.id = id2;
    exports.stripFlags = stripFlags;
    exports.stripComment = stripComment;
    exports.preparePath = preparePath;
    exports.prepareMustache = prepareMustache;
    exports.prepareRawBlock = prepareRawBlock;
    exports.prepareBlock = prepareBlock;
    exports.prepareProgram = prepareProgram;
    exports.preparePartialBlock = preparePartialBlock;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _exception = require_exception();
    var _exception2 = _interopRequireDefault(_exception);
    function validateClose(open, close) {
      close = close.path ? close.path.original : close;
      if (open.path.original !== close) {
        var errorNode = { loc: open.path.loc };
        throw new _exception2["default"](open.path.original + " doesn't match " + close, errorNode);
      }
    }
    function SourceLocation(source, locInfo) {
      this.source = source;
      this.start = {
        line: locInfo.first_line,
        column: locInfo.first_column
      };
      this.end = {
        line: locInfo.last_line,
        column: locInfo.last_column
      };
    }
    function id2(token) {
      if (/^\[.*\]$/.test(token)) {
        return token.substring(1, token.length - 1);
      } else {
        return token;
      }
    }
    function stripFlags(open, close) {
      return {
        open: open.charAt(2) === "~",
        close: close.charAt(close.length - 3) === "~"
      };
    }
    function stripComment(comment) {
      return comment.replace(/^\{\{~?!-?-?/, "").replace(/-?-?~?\}\}$/, "");
    }
    function preparePath(data, parts, loc) {
      loc = this.locInfo(loc);
      var original = data ? "@" : "", dig = [], depth = 0;
      for (var i = 0, l2 = parts.length; i < l2; i++) {
        var part = parts[i].part, isLiteral = parts[i].original !== part;
        original += (parts[i].separator || "") + part;
        if (!isLiteral && (part === ".." || part === "." || part === "this")) {
          if (dig.length > 0) {
            throw new _exception2["default"]("Invalid path: " + original, { loc });
          } else if (part === "..") {
            depth++;
          }
        } else {
          dig.push(part);
        }
      }
      return {
        type: "PathExpression",
        data,
        depth,
        parts: dig,
        original,
        loc
      };
    }
    function prepareMustache(path2, params, hash2, open, strip, locInfo) {
      var escapeFlag = open.charAt(3) || open.charAt(2), escaped = escapeFlag !== "{" && escapeFlag !== "&";
      var decorator = /\*/.test(open);
      return {
        type: decorator ? "Decorator" : "MustacheStatement",
        path: path2,
        params,
        hash: hash2,
        escaped,
        strip,
        loc: this.locInfo(locInfo)
      };
    }
    function prepareRawBlock(openRawBlock, contents, close, locInfo) {
      validateClose(openRawBlock, close);
      locInfo = this.locInfo(locInfo);
      var program = {
        type: "Program",
        body: contents,
        strip: {},
        loc: locInfo
      };
      return {
        type: "BlockStatement",
        path: openRawBlock.path,
        params: openRawBlock.params,
        hash: openRawBlock.hash,
        program,
        openStrip: {},
        inverseStrip: {},
        closeStrip: {},
        loc: locInfo
      };
    }
    function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
      if (close && close.path) {
        validateClose(openBlock, close);
      }
      var decorator = /\*/.test(openBlock.open);
      program.blockParams = openBlock.blockParams;
      var inverse = void 0, inverseStrip = void 0;
      if (inverseAndProgram) {
        if (decorator) {
          throw new _exception2["default"]("Unexpected inverse block on decorator", inverseAndProgram);
        }
        if (inverseAndProgram.chain) {
          inverseAndProgram.program.body[0].closeStrip = close.strip;
        }
        inverseStrip = inverseAndProgram.strip;
        inverse = inverseAndProgram.program;
      }
      if (inverted) {
        inverted = inverse;
        inverse = program;
        program = inverted;
      }
      return {
        type: decorator ? "DecoratorBlock" : "BlockStatement",
        path: openBlock.path,
        params: openBlock.params,
        hash: openBlock.hash,
        program,
        inverse,
        openStrip: openBlock.strip,
        inverseStrip,
        closeStrip: close && close.strip,
        loc: this.locInfo(locInfo)
      };
    }
    function prepareProgram(statements, loc) {
      if (!loc && statements.length) {
        var firstLoc = statements[0].loc, lastLoc = statements[statements.length - 1].loc;
        if (firstLoc && lastLoc) {
          loc = {
            source: firstLoc.source,
            start: {
              line: firstLoc.start.line,
              column: firstLoc.start.column
            },
            end: {
              line: lastLoc.end.line,
              column: lastLoc.end.column
            }
          };
        }
      }
      return {
        type: "Program",
        body: statements,
        strip: {},
        loc
      };
    }
    function preparePartialBlock(open, program, close, locInfo) {
      validateClose(open, close);
      return {
        type: "PartialBlockStatement",
        name: open.path,
        params: open.params,
        hash: open.hash,
        program,
        openStrip: open.strip,
        closeStrip: close && close.strip,
        loc: this.locInfo(locInfo)
      };
    }
  }
});

// node_modules/handlebars/dist/cjs/handlebars/compiler/base.js
var require_base2 = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/compiler/base.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.parseWithoutProcessing = parseWithoutProcessing;
    exports.parse = parse5;
    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      } else {
        var newObj = {};
        if (obj != null) {
          for (var key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
          }
        }
        newObj["default"] = obj;
        return newObj;
      }
    }
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _parser = require_parser();
    var _parser2 = _interopRequireDefault(_parser);
    var _whitespaceControl = require_whitespace_control();
    var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
    var _helpers = require_helpers2();
    var Helpers = _interopRequireWildcard(_helpers);
    var _exception = require_exception();
    var _exception2 = _interopRequireDefault(_exception);
    var _utils = require_utils();
    exports.parser = _parser2["default"];
    var yy = {};
    _utils.extend(yy, Helpers);
    function parseWithoutProcessing(input, options) {
      if (input.type === "Program") {
        validateInputAst(input);
        return input;
      }
      _parser2["default"].yy = yy;
      yy.locInfo = function(locInfo) {
        return new yy.SourceLocation(options && options.srcName, locInfo);
      };
      var ast = _parser2["default"].parse(input);
      return ast;
    }
    function parse5(input, options) {
      var ast = parseWithoutProcessing(input, options);
      var strip = new _whitespaceControl2["default"](options);
      return strip.accept(ast);
    }
    function validateInputAst(ast) {
      validateAstNode(ast);
    }
    function validateAstNode(node) {
      if (node == null) {
        return;
      }
      if (Array.isArray(node)) {
        node.forEach(validateAstNode);
        return;
      }
      if (typeof node !== "object") {
        return;
      }
      if (node.type === "PathExpression") {
        if (!isValidDepth(node.depth)) {
          throw new _exception2["default"]("Invalid AST: PathExpression.depth must be an integer");
        }
        if (!Array.isArray(node.parts)) {
          throw new _exception2["default"]("Invalid AST: PathExpression.parts must be an array");
        }
        for (var i = 0; i < node.parts.length; i++) {
          if (typeof node.parts[i] !== "string") {
            throw new _exception2["default"]("Invalid AST: PathExpression.parts must only contain strings");
          }
        }
      } else if (node.type === "NumberLiteral") {
        if (typeof node.value !== "number" || !isFinite(node.value)) {
          throw new _exception2["default"]("Invalid AST: NumberLiteral.value must be a number");
        }
      } else if (node.type === "BooleanLiteral") {
        if (typeof node.value !== "boolean") {
          throw new _exception2["default"]("Invalid AST: BooleanLiteral.value must be a boolean");
        }
      }
      Object.keys(node).forEach(function(propertyName) {
        if (propertyName === "loc") {
          return;
        }
        validateAstNode(node[propertyName]);
      });
    }
    function isValidDepth(depth) {
      return typeof depth === "number" && isFinite(depth) && Math.floor(depth) === depth && depth >= 0;
    }
  }
});

// node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js
var require_compiler = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.Compiler = Compiler;
    exports.precompile = precompile;
    exports.compile = compile;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _exception = require_exception();
    var _exception2 = _interopRequireDefault(_exception);
    var _utils = require_utils();
    var _ast = require_ast();
    var _ast2 = _interopRequireDefault(_ast);
    var slice2 = [].slice;
    function Compiler() {
    }
    Compiler.prototype = {
      compiler: Compiler,
      equals: function equals(other) {
        var len = this.opcodes.length;
        if (other.opcodes.length !== len) {
          return false;
        }
        for (var i = 0; i < len; i++) {
          var opcode = this.opcodes[i], otherOpcode = other.opcodes[i];
          if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
            return false;
          }
        }
        len = this.children.length;
        for (var i = 0; i < len; i++) {
          if (!this.children[i].equals(other.children[i])) {
            return false;
          }
        }
        return true;
      },
      guid: 0,
      compile: function compile2(program, options) {
        this.sourceNode = [];
        this.opcodes = [];
        this.children = [];
        this.options = options;
        this.stringParams = options.stringParams;
        this.trackIds = options.trackIds;
        options.blockParams = options.blockParams || [];
        options.knownHelpers = _utils.extend(/* @__PURE__ */ Object.create(null), {
          helperMissing: true,
          blockHelperMissing: true,
          each: true,
          "if": true,
          unless: true,
          "with": true,
          log: true,
          lookup: true
        }, options.knownHelpers);
        return this.accept(program);
      },
      compileProgram: function compileProgram(program) {
        var childCompiler = new this.compiler(), result = childCompiler.compile(program, this.options), guid3 = this.guid++;
        this.usePartial = this.usePartial || result.usePartial;
        this.children[guid3] = result;
        this.useDepths = this.useDepths || result.useDepths;
        return guid3;
      },
      accept: function accept(node) {
        if (!this[node.type]) {
          throw new _exception2["default"]("Unknown type: " + node.type, node);
        }
        this.sourceNode.unshift(node);
        var ret = this[node.type](node);
        this.sourceNode.shift();
        return ret;
      },
      Program: function Program(program) {
        this.options.blockParams.unshift(program.blockParams);
        var body = program.body, bodyLength = body.length;
        for (var i = 0; i < bodyLength; i++) {
          this.accept(body[i]);
        }
        this.options.blockParams.shift();
        this.isSimple = bodyLength === 1;
        this.blockParams = program.blockParams ? program.blockParams.length : 0;
        return this;
      },
      BlockStatement: function BlockStatement(block) {
        transformLiteralToPath(block);
        var program = block.program, inverse = block.inverse;
        program = program && this.compileProgram(program);
        inverse = inverse && this.compileProgram(inverse);
        var type = this.classifySexpr(block);
        if (type === "helper") {
          this.helperSexpr(block, program, inverse);
        } else if (type === "simple") {
          this.simpleSexpr(block);
          this.opcode("pushProgram", program);
          this.opcode("pushProgram", inverse);
          this.opcode("emptyHash");
          this.opcode("blockValue", block.path.original);
        } else {
          this.ambiguousSexpr(block, program, inverse);
          this.opcode("pushProgram", program);
          this.opcode("pushProgram", inverse);
          this.opcode("emptyHash");
          this.opcode("ambiguousBlockValue");
        }
        this.opcode("append");
      },
      DecoratorBlock: function DecoratorBlock(decorator) {
        var program = decorator.program && this.compileProgram(decorator.program);
        var params = this.setupFullMustacheParams(decorator, program, void 0), path2 = decorator.path;
        this.useDecorators = true;
        this.opcode("registerDecorator", params.length, path2.original);
      },
      PartialStatement: function PartialStatement(partial2) {
        this.usePartial = true;
        var program = partial2.program;
        if (program) {
          program = this.compileProgram(partial2.program);
        }
        var params = partial2.params;
        if (params.length > 1) {
          throw new _exception2["default"]("Unsupported number of partial arguments: " + params.length, partial2);
        } else if (!params.length) {
          if (this.options.explicitPartialContext) {
            this.opcode("pushLiteral", "undefined");
          } else {
            params.push({ type: "PathExpression", parts: [], depth: 0 });
          }
        }
        var partialName = partial2.name.original, isDynamic = partial2.name.type === "SubExpression";
        if (isDynamic) {
          this.accept(partial2.name);
        }
        this.setupFullMustacheParams(partial2, program, void 0, true);
        var indent = partial2.indent || "";
        if (this.options.preventIndent && indent) {
          this.opcode("appendContent", indent);
          indent = "";
        }
        this.opcode("invokePartial", isDynamic, partialName, indent);
        this.opcode("append");
      },
      PartialBlockStatement: function PartialBlockStatement(partialBlock) {
        this.PartialStatement(partialBlock);
      },
      MustacheStatement: function MustacheStatement(mustache) {
        this.SubExpression(mustache);
        if (mustache.escaped && !this.options.noEscape) {
          this.opcode("appendEscaped");
        } else {
          this.opcode("append");
        }
      },
      Decorator: function Decorator(decorator) {
        this.DecoratorBlock(decorator);
      },
      ContentStatement: function ContentStatement(content) {
        if (content.value) {
          this.opcode("appendContent", content.value);
        }
      },
      CommentStatement: function CommentStatement() {
      },
      SubExpression: function SubExpression(sexpr) {
        transformLiteralToPath(sexpr);
        var type = this.classifySexpr(sexpr);
        if (type === "simple") {
          this.simpleSexpr(sexpr);
        } else if (type === "helper") {
          this.helperSexpr(sexpr);
        } else {
          this.ambiguousSexpr(sexpr);
        }
      },
      ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
        var path2 = sexpr.path, name = path2.parts[0], isBlock = program != null || inverse != null;
        this.opcode("getContext", path2.depth);
        this.opcode("pushProgram", program);
        this.opcode("pushProgram", inverse);
        path2.strict = true;
        this.accept(path2);
        this.opcode("invokeAmbiguous", name, isBlock);
      },
      simpleSexpr: function simpleSexpr(sexpr) {
        var path2 = sexpr.path;
        path2.strict = true;
        this.accept(path2);
        this.opcode("resolvePossibleLambda");
      },
      helperSexpr: function helperSexpr(sexpr, program, inverse) {
        var params = this.setupFullMustacheParams(sexpr, program, inverse), path2 = sexpr.path, name = path2.parts[0];
        if (this.options.knownHelpers[name]) {
          this.opcode("invokeKnownHelper", params.length, name);
        } else if (this.options.knownHelpersOnly) {
          throw new _exception2["default"]("You specified knownHelpersOnly, but used the unknown helper " + name, sexpr);
        } else {
          path2.strict = true;
          path2.falsy = true;
          this.accept(path2);
          this.opcode("invokeHelper", params.length, path2.original, _ast2["default"].helpers.simpleId(path2));
        }
      },
      PathExpression: function PathExpression(path2) {
        this.addDepth(path2.depth);
        this.opcode("getContext", path2.depth);
        var name = path2.parts[0], scoped = _ast2["default"].helpers.scopedId(path2), blockParamId = !path2.depth && !scoped && this.blockParamIndex(name);
        if (blockParamId) {
          this.opcode("lookupBlockParam", blockParamId, path2.parts);
        } else if (!name) {
          this.opcode("pushContext");
        } else if (path2.data) {
          this.options.data = true;
          this.opcode("lookupData", path2.depth, path2.parts, path2.strict);
        } else {
          this.opcode("lookupOnContext", path2.parts, path2.falsy, path2.strict, scoped);
        }
      },
      StringLiteral: function StringLiteral(string4) {
        this.opcode("pushString", string4.value);
      },
      NumberLiteral: function NumberLiteral(number8) {
        this.opcode("pushLiteral", number8.value);
      },
      BooleanLiteral: function BooleanLiteral(bool) {
        this.opcode("pushLiteral", bool.value);
      },
      UndefinedLiteral: function UndefinedLiteral() {
        this.opcode("pushLiteral", "undefined");
      },
      NullLiteral: function NullLiteral() {
        this.opcode("pushLiteral", "null");
      },
      Hash: function Hash(hash2) {
        var pairs = hash2.pairs, i = 0, l2 = pairs.length;
        this.opcode("pushHash");
        for (; i < l2; i++) {
          this.pushParam(pairs[i].value);
        }
        while (i--) {
          this.opcode("assignToHash", pairs[i].key);
        }
        this.opcode("popHash");
      },
      // HELPERS
      opcode: function opcode(name) {
        this.opcodes.push({
          opcode: name,
          args: slice2.call(arguments, 1),
          loc: this.sourceNode[0].loc
        });
      },
      addDepth: function addDepth(depth) {
        if (!depth) {
          return;
        }
        this.useDepths = true;
      },
      classifySexpr: function classifySexpr(sexpr) {
        var isSimple = _ast2["default"].helpers.simpleId(sexpr.path);
        var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
        var isHelper = !isBlockParam && _ast2["default"].helpers.helperExpression(sexpr);
        var isEligible = !isBlockParam && (isHelper || isSimple);
        if (isEligible && !isHelper) {
          var _name = sexpr.path.parts[0], options = this.options;
          if (options.knownHelpers[_name]) {
            isHelper = true;
          } else if (options.knownHelpersOnly) {
            isEligible = false;
          }
        }
        if (isHelper) {
          return "helper";
        } else if (isEligible) {
          return "ambiguous";
        } else {
          return "simple";
        }
      },
      pushParams: function pushParams(params) {
        for (var i = 0, l2 = params.length; i < l2; i++) {
          this.pushParam(params[i]);
        }
      },
      pushParam: function pushParam(val) {
        var value = val.value != null ? val.value : val.original || "";
        if (this.stringParams) {
          if (value.replace) {
            value = value.replace(/^(\.?\.\/)*/g, "").replace(/\//g, ".");
          }
          if (val.depth) {
            this.addDepth(val.depth);
          }
          this.opcode("getContext", val.depth || 0);
          this.opcode("pushStringParam", value, val.type);
          if (val.type === "SubExpression") {
            this.accept(val);
          }
        } else {
          if (this.trackIds) {
            var blockParamIndex = void 0;
            if (val.parts && !_ast2["default"].helpers.scopedId(val) && !val.depth) {
              blockParamIndex = this.blockParamIndex(val.parts[0]);
            }
            if (blockParamIndex) {
              var blockParamChild = val.parts.slice(1).join(".");
              this.opcode("pushId", "BlockParam", blockParamIndex, blockParamChild);
            } else {
              value = val.original || value;
              if (value.replace) {
                value = value.replace(/^this(?:\.|$)/, "").replace(/^\.\//, "").replace(/^\.$/, "");
              }
              this.opcode("pushId", val.type, value);
            }
          }
          this.accept(val);
        }
      },
      setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
        var params = sexpr.params;
        this.pushParams(params);
        this.opcode("pushProgram", program);
        this.opcode("pushProgram", inverse);
        if (sexpr.hash) {
          this.accept(sexpr.hash);
        } else {
          this.opcode("emptyHash", omitEmpty);
        }
        return params;
      },
      blockParamIndex: function blockParamIndex(name) {
        for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
          var blockParams = this.options.blockParams[depth], param = blockParams && _utils.indexOf(blockParams, name);
          if (blockParams && param >= 0) {
            return [depth, param];
          }
        }
      }
    };
    function precompile(input, options, env) {
      if (input == null || typeof input !== "string" && input.type !== "Program") {
        throw new _exception2["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed " + input);
      }
      options = options || {};
      if (!("data" in options)) {
        options.data = true;
      }
      if (options.compat) {
        options.useDepths = true;
      }
      var ast = env.parse(input, options), environment = new env.Compiler().compile(ast, options);
      return new env.JavaScriptCompiler().compile(environment, options);
    }
    function compile(input, options, env) {
      if (options === void 0) options = {};
      if (input == null || typeof input !== "string" && input.type !== "Program") {
        throw new _exception2["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed " + input);
      }
      options = _utils.extend({}, options);
      if (!("data" in options)) {
        options.data = true;
      }
      if (options.compat) {
        options.useDepths = true;
      }
      var compiled = void 0;
      function compileInput() {
        var ast = env.parse(input, options), environment = new env.Compiler().compile(ast, options), templateSpec = new env.JavaScriptCompiler().compile(environment, options, void 0, true);
        return env.template(templateSpec);
      }
      function ret(context, execOptions) {
        if (!compiled) {
          compiled = compileInput();
        }
        return compiled.call(this, context, execOptions);
      }
      ret._setup = function(setupOptions) {
        if (!compiled) {
          compiled = compileInput();
        }
        return compiled._setup(setupOptions);
      };
      ret._child = function(i, data, blockParams, depths) {
        if (!compiled) {
          compiled = compileInput();
        }
        return compiled._child(i, data, blockParams, depths);
      };
      return ret;
    }
    function argEquals(a, b) {
      if (a === b) {
        return true;
      }
      if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
        for (var i = 0; i < a.length; i++) {
          if (!argEquals(a[i], b[i])) {
            return false;
          }
        }
        return true;
      }
    }
    function transformLiteralToPath(sexpr) {
      if (!sexpr.path.parts) {
        var literal2 = sexpr.path;
        sexpr.path = {
          type: "PathExpression",
          data: false,
          depth: 0,
          parts: [literal2.original + ""],
          original: literal2.original + "",
          loc: literal2.loc
        };
      }
    }
  }
});

// node_modules/source-map/lib/base64.js
var require_base64 = __commonJS({
  "node_modules/source-map/lib/base64.js"(exports) {
    var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
    exports.encode = function(number8) {
      if (0 <= number8 && number8 < intToCharMap.length) {
        return intToCharMap[number8];
      }
      throw new TypeError("Must be between 0 and 63: " + number8);
    };
    exports.decode = function(charCode) {
      var bigA = 65;
      var bigZ = 90;
      var littleA = 97;
      var littleZ = 122;
      var zero3 = 48;
      var nine = 57;
      var plus = 43;
      var slash = 47;
      var littleOffset = 26;
      var numberOffset = 52;
      if (bigA <= charCode && charCode <= bigZ) {
        return charCode - bigA;
      }
      if (littleA <= charCode && charCode <= littleZ) {
        return charCode - littleA + littleOffset;
      }
      if (zero3 <= charCode && charCode <= nine) {
        return charCode - zero3 + numberOffset;
      }
      if (charCode == plus) {
        return 62;
      }
      if (charCode == slash) {
        return 63;
      }
      return -1;
    };
  }
});

// node_modules/source-map/lib/base64-vlq.js
var require_base64_vlq = __commonJS({
  "node_modules/source-map/lib/base64-vlq.js"(exports) {
    var base643 = require_base64();
    var VLQ_BASE_SHIFT = 5;
    var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
    var VLQ_BASE_MASK = VLQ_BASE - 1;
    var VLQ_CONTINUATION_BIT = VLQ_BASE;
    function toVLQSigned(aValue) {
      return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
    }
    function fromVLQSigned(aValue) {
      var isNegative = (aValue & 1) === 1;
      var shifted = aValue >> 1;
      return isNegative ? -shifted : shifted;
    }
    exports.encode = function base64VLQ_encode(aValue) {
      var encoded = "";
      var digit;
      var vlq = toVLQSigned(aValue);
      do {
        digit = vlq & VLQ_BASE_MASK;
        vlq >>>= VLQ_BASE_SHIFT;
        if (vlq > 0) {
          digit |= VLQ_CONTINUATION_BIT;
        }
        encoded += base643.encode(digit);
      } while (vlq > 0);
      return encoded;
    };
    exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
      var strLen = aStr.length;
      var result = 0;
      var shift = 0;
      var continuation, digit;
      do {
        if (aIndex >= strLen) {
          throw new Error("Expected more digits in base 64 VLQ value.");
        }
        digit = base643.decode(aStr.charCodeAt(aIndex++));
        if (digit === -1) {
          throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
        }
        continuation = !!(digit & VLQ_CONTINUATION_BIT);
        digit &= VLQ_BASE_MASK;
        result = result + (digit << shift);
        shift += VLQ_BASE_SHIFT;
      } while (continuation);
      aOutParam.value = fromVLQSigned(result);
      aOutParam.rest = aIndex;
    };
  }
});

// node_modules/source-map/lib/util.js
var require_util = __commonJS({
  "node_modules/source-map/lib/util.js"(exports) {
    function getArg(aArgs, aName, aDefaultValue) {
      if (aName in aArgs) {
        return aArgs[aName];
      } else if (arguments.length === 3) {
        return aDefaultValue;
      } else {
        throw new Error('"' + aName + '" is a required argument.');
      }
    }
    exports.getArg = getArg;
    var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
    var dataUrlRegexp = /^data:.+\,.+$/;
    function urlParse(aUrl) {
      var match2 = aUrl.match(urlRegexp);
      if (!match2) {
        return null;
      }
      return {
        scheme: match2[1],
        auth: match2[2],
        host: match2[3],
        port: match2[4],
        path: match2[5]
      };
    }
    exports.urlParse = urlParse;
    function urlGenerate(aParsedUrl) {
      var url2 = "";
      if (aParsedUrl.scheme) {
        url2 += aParsedUrl.scheme + ":";
      }
      url2 += "//";
      if (aParsedUrl.auth) {
        url2 += aParsedUrl.auth + "@";
      }
      if (aParsedUrl.host) {
        url2 += aParsedUrl.host;
      }
      if (aParsedUrl.port) {
        url2 += ":" + aParsedUrl.port;
      }
      if (aParsedUrl.path) {
        url2 += aParsedUrl.path;
      }
      return url2;
    }
    exports.urlGenerate = urlGenerate;
    function normalize2(aPath) {
      var path2 = aPath;
      var url2 = urlParse(aPath);
      if (url2) {
        if (!url2.path) {
          return aPath;
        }
        path2 = url2.path;
      }
      var isAbsolute = exports.isAbsolute(path2);
      var parts = path2.split(/\/+/);
      for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
        part = parts[i];
        if (part === ".") {
          parts.splice(i, 1);
        } else if (part === "..") {
          up++;
        } else if (up > 0) {
          if (part === "") {
            parts.splice(i + 1, up);
            up = 0;
          } else {
            parts.splice(i, 2);
            up--;
          }
        }
      }
      path2 = parts.join("/");
      if (path2 === "") {
        path2 = isAbsolute ? "/" : ".";
      }
      if (url2) {
        url2.path = path2;
        return urlGenerate(url2);
      }
      return path2;
    }
    exports.normalize = normalize2;
    function join(aRoot, aPath) {
      if (aRoot === "") {
        aRoot = ".";
      }
      if (aPath === "") {
        aPath = ".";
      }
      var aPathUrl = urlParse(aPath);
      var aRootUrl = urlParse(aRoot);
      if (aRootUrl) {
        aRoot = aRootUrl.path || "/";
      }
      if (aPathUrl && !aPathUrl.scheme) {
        if (aRootUrl) {
          aPathUrl.scheme = aRootUrl.scheme;
        }
        return urlGenerate(aPathUrl);
      }
      if (aPathUrl || aPath.match(dataUrlRegexp)) {
        return aPath;
      }
      if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
        aRootUrl.host = aPath;
        return urlGenerate(aRootUrl);
      }
      var joined = aPath.charAt(0) === "/" ? aPath : normalize2(aRoot.replace(/\/+$/, "") + "/" + aPath);
      if (aRootUrl) {
        aRootUrl.path = joined;
        return urlGenerate(aRootUrl);
      }
      return joined;
    }
    exports.join = join;
    exports.isAbsolute = function(aPath) {
      return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
    };
    function relative(aRoot, aPath) {
      if (aRoot === "") {
        aRoot = ".";
      }
      aRoot = aRoot.replace(/\/$/, "");
      var level = 0;
      while (aPath.indexOf(aRoot + "/") !== 0) {
        var index = aRoot.lastIndexOf("/");
        if (index < 0) {
          return aPath;
        }
        aRoot = aRoot.slice(0, index);
        if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
          return aPath;
        }
        ++level;
      }
      return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
    }
    exports.relative = relative;
    var supportsNullProto = (function() {
      var obj = /* @__PURE__ */ Object.create(null);
      return !("__proto__" in obj);
    })();
    function identity3(s2) {
      return s2;
    }
    function toSetString(aStr) {
      if (isProtoString(aStr)) {
        return "$" + aStr;
      }
      return aStr;
    }
    exports.toSetString = supportsNullProto ? identity3 : toSetString;
    function fromSetString(aStr) {
      if (isProtoString(aStr)) {
        return aStr.slice(1);
      }
      return aStr;
    }
    exports.fromSetString = supportsNullProto ? identity3 : fromSetString;
    function isProtoString(s2) {
      if (!s2) {
        return false;
      }
      var length = s2.length;
      if (length < 9) {
        return false;
      }
      if (s2.charCodeAt(length - 1) !== 95 || s2.charCodeAt(length - 2) !== 95 || s2.charCodeAt(length - 3) !== 111 || s2.charCodeAt(length - 4) !== 116 || s2.charCodeAt(length - 5) !== 111 || s2.charCodeAt(length - 6) !== 114 || s2.charCodeAt(length - 7) !== 112 || s2.charCodeAt(length - 8) !== 95 || s2.charCodeAt(length - 9) !== 95) {
        return false;
      }
      for (var i = length - 10; i >= 0; i--) {
        if (s2.charCodeAt(i) !== 36) {
          return false;
        }
      }
      return true;
    }
    function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
      var cmp = strcmp(mappingA.source, mappingB.source);
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalLine - mappingB.originalLine;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalColumn - mappingB.originalColumn;
      if (cmp !== 0 || onlyCompareOriginal) {
        return cmp;
      }
      cmp = mappingA.generatedColumn - mappingB.generatedColumn;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.generatedLine - mappingB.generatedLine;
      if (cmp !== 0) {
        return cmp;
      }
      return strcmp(mappingA.name, mappingB.name);
    }
    exports.compareByOriginalPositions = compareByOriginalPositions;
    function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
      var cmp = mappingA.generatedLine - mappingB.generatedLine;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.generatedColumn - mappingB.generatedColumn;
      if (cmp !== 0 || onlyCompareGenerated) {
        return cmp;
      }
      cmp = strcmp(mappingA.source, mappingB.source);
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalLine - mappingB.originalLine;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalColumn - mappingB.originalColumn;
      if (cmp !== 0) {
        return cmp;
      }
      return strcmp(mappingA.name, mappingB.name);
    }
    exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
    function strcmp(aStr1, aStr2) {
      if (aStr1 === aStr2) {
        return 0;
      }
      if (aStr1 === null) {
        return 1;
      }
      if (aStr2 === null) {
        return -1;
      }
      if (aStr1 > aStr2) {
        return 1;
      }
      return -1;
    }
    function compareByGeneratedPositionsInflated(mappingA, mappingB) {
      var cmp = mappingA.generatedLine - mappingB.generatedLine;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.generatedColumn - mappingB.generatedColumn;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = strcmp(mappingA.source, mappingB.source);
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalLine - mappingB.originalLine;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalColumn - mappingB.originalColumn;
      if (cmp !== 0) {
        return cmp;
      }
      return strcmp(mappingA.name, mappingB.name);
    }
    exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
    function parseSourceMapInput(str) {
      return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
    }
    exports.parseSourceMapInput = parseSourceMapInput;
    function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
      sourceURL = sourceURL || "";
      if (sourceRoot) {
        if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") {
          sourceRoot += "/";
        }
        sourceURL = sourceRoot + sourceURL;
      }
      if (sourceMapURL) {
        var parsed = urlParse(sourceMapURL);
        if (!parsed) {
          throw new Error("sourceMapURL could not be parsed");
        }
        if (parsed.path) {
          var index = parsed.path.lastIndexOf("/");
          if (index >= 0) {
            parsed.path = parsed.path.substring(0, index + 1);
          }
        }
        sourceURL = join(urlGenerate(parsed), sourceURL);
      }
      return normalize2(sourceURL);
    }
    exports.computeSourceURL = computeSourceURL;
  }
});

// node_modules/source-map/lib/array-set.js
var require_array_set = __commonJS({
  "node_modules/source-map/lib/array-set.js"(exports) {
    var util = require_util();
    var has = Object.prototype.hasOwnProperty;
    var hasNativeMap = typeof Map !== "undefined";
    function ArraySet() {
      this._array = [];
      this._set = hasNativeMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null);
    }
    ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
      var set4 = new ArraySet();
      for (var i = 0, len = aArray.length; i < len; i++) {
        set4.add(aArray[i], aAllowDuplicates);
      }
      return set4;
    };
    ArraySet.prototype.size = function ArraySet_size() {
      return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
    };
    ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
      var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
      var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
      var idx = this._array.length;
      if (!isDuplicate || aAllowDuplicates) {
        this._array.push(aStr);
      }
      if (!isDuplicate) {
        if (hasNativeMap) {
          this._set.set(aStr, idx);
        } else {
          this._set[sStr] = idx;
        }
      }
    };
    ArraySet.prototype.has = function ArraySet_has(aStr) {
      if (hasNativeMap) {
        return this._set.has(aStr);
      } else {
        var sStr = util.toSetString(aStr);
        return has.call(this._set, sStr);
      }
    };
    ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
      if (hasNativeMap) {
        var idx = this._set.get(aStr);
        if (idx >= 0) {
          return idx;
        }
      } else {
        var sStr = util.toSetString(aStr);
        if (has.call(this._set, sStr)) {
          return this._set[sStr];
        }
      }
      throw new Error('"' + aStr + '" is not in the set.');
    };
    ArraySet.prototype.at = function ArraySet_at(aIdx) {
      if (aIdx >= 0 && aIdx < this._array.length) {
        return this._array[aIdx];
      }
      throw new Error("No element indexed by " + aIdx);
    };
    ArraySet.prototype.toArray = function ArraySet_toArray() {
      return this._array.slice();
    };
    exports.ArraySet = ArraySet;
  }
});

// node_modules/source-map/lib/mapping-list.js
var require_mapping_list = __commonJS({
  "node_modules/source-map/lib/mapping-list.js"(exports) {
    var util = require_util();
    function generatedPositionAfter(mappingA, mappingB) {
      var lineA = mappingA.generatedLine;
      var lineB = mappingB.generatedLine;
      var columnA = mappingA.generatedColumn;
      var columnB = mappingB.generatedColumn;
      return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
    }
    function MappingList() {
      this._array = [];
      this._sorted = true;
      this._last = { generatedLine: -1, generatedColumn: 0 };
    }
    MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) {
      this._array.forEach(aCallback, aThisArg);
    };
    MappingList.prototype.add = function MappingList_add(aMapping) {
      if (generatedPositionAfter(this._last, aMapping)) {
        this._last = aMapping;
        this._array.push(aMapping);
      } else {
        this._sorted = false;
        this._array.push(aMapping);
      }
    };
    MappingList.prototype.toArray = function MappingList_toArray() {
      if (!this._sorted) {
        this._array.sort(util.compareByGeneratedPositionsInflated);
        this._sorted = true;
      }
      return this._array;
    };
    exports.MappingList = MappingList;
  }
});

// node_modules/source-map/lib/source-map-generator.js
var require_source_map_generator = __commonJS({
  "node_modules/source-map/lib/source-map-generator.js"(exports) {
    var base64VLQ = require_base64_vlq();
    var util = require_util();
    var ArraySet = require_array_set().ArraySet;
    var MappingList = require_mapping_list().MappingList;
    function SourceMapGenerator(aArgs) {
      if (!aArgs) {
        aArgs = {};
      }
      this._file = util.getArg(aArgs, "file", null);
      this._sourceRoot = util.getArg(aArgs, "sourceRoot", null);
      this._skipValidation = util.getArg(aArgs, "skipValidation", false);
      this._sources = new ArraySet();
      this._names = new ArraySet();
      this._mappings = new MappingList();
      this._sourcesContents = null;
    }
    SourceMapGenerator.prototype._version = 3;
    SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
      var sourceRoot = aSourceMapConsumer.sourceRoot;
      var generator = new SourceMapGenerator({
        file: aSourceMapConsumer.file,
        sourceRoot
      });
      aSourceMapConsumer.eachMapping(function(mapping) {
        var newMapping = {
          generated: {
            line: mapping.generatedLine,
            column: mapping.generatedColumn
          }
        };
        if (mapping.source != null) {
          newMapping.source = mapping.source;
          if (sourceRoot != null) {
            newMapping.source = util.relative(sourceRoot, newMapping.source);
          }
          newMapping.original = {
            line: mapping.originalLine,
            column: mapping.originalColumn
          };
          if (mapping.name != null) {
            newMapping.name = mapping.name;
          }
        }
        generator.addMapping(newMapping);
      });
      aSourceMapConsumer.sources.forEach(function(sourceFile) {
        var sourceRelative = sourceFile;
        if (sourceRoot !== null) {
          sourceRelative = util.relative(sourceRoot, sourceFile);
        }
        if (!generator._sources.has(sourceRelative)) {
          generator._sources.add(sourceRelative);
        }
        var content = aSourceMapConsumer.sourceContentFor(sourceFile);
        if (content != null) {
          generator.setSourceContent(sourceFile, content);
        }
      });
      return generator;
    };
    SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) {
      var generated = util.getArg(aArgs, "generated");
      var original = util.getArg(aArgs, "original", null);
      var source = util.getArg(aArgs, "source", null);
      var name = util.getArg(aArgs, "name", null);
      if (!this._skipValidation) {
        this._validateMapping(generated, original, source, name);
      }
      if (source != null) {
        source = String(source);
        if (!this._sources.has(source)) {
          this._sources.add(source);
        }
      }
      if (name != null) {
        name = String(name);
        if (!this._names.has(name)) {
          this._names.add(name);
        }
      }
      this._mappings.add({
        generatedLine: generated.line,
        generatedColumn: generated.column,
        originalLine: original != null && original.line,
        originalColumn: original != null && original.column,
        source,
        name
      });
    };
    SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
      var source = aSourceFile;
      if (this._sourceRoot != null) {
        source = util.relative(this._sourceRoot, source);
      }
      if (aSourceContent != null) {
        if (!this._sourcesContents) {
          this._sourcesContents = /* @__PURE__ */ Object.create(null);
        }
        this._sourcesContents[util.toSetString(source)] = aSourceContent;
      } else if (this._sourcesContents) {
        delete this._sourcesContents[util.toSetString(source)];
        if (Object.keys(this._sourcesContents).length === 0) {
          this._sourcesContents = null;
        }
      }
    };
    SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
      var sourceFile = aSourceFile;
      if (aSourceFile == null) {
        if (aSourceMapConsumer.file == null) {
          throw new Error(
            `SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`
          );
        }
        sourceFile = aSourceMapConsumer.file;
      }
      var sourceRoot = this._sourceRoot;
      if (sourceRoot != null) {
        sourceFile = util.relative(sourceRoot, sourceFile);
      }
      var newSources = new ArraySet();
      var newNames = new ArraySet();
      this._mappings.unsortedForEach(function(mapping) {
        if (mapping.source === sourceFile && mapping.originalLine != null) {
          var original = aSourceMapConsumer.originalPositionFor({
            line: mapping.originalLine,
            column: mapping.originalColumn
          });
          if (original.source != null) {
            mapping.source = original.source;
            if (aSourceMapPath != null) {
              mapping.source = util.join(aSourceMapPath, mapping.source);
            }
            if (sourceRoot != null) {
              mapping.source = util.relative(sourceRoot, mapping.source);
            }
            mapping.originalLine = original.line;
            mapping.originalColumn = original.column;
            if (original.name != null) {
              mapping.name = original.name;
            }
          }
        }
        var source = mapping.source;
        if (source != null && !newSources.has(source)) {
          newSources.add(source);
        }
        var name = mapping.name;
        if (name != null && !newNames.has(name)) {
          newNames.add(name);
        }
      }, this);
      this._sources = newSources;
      this._names = newNames;
      aSourceMapConsumer.sources.forEach(function(sourceFile2) {
        var content = aSourceMapConsumer.sourceContentFor(sourceFile2);
        if (content != null) {
          if (aSourceMapPath != null) {
            sourceFile2 = util.join(aSourceMapPath, sourceFile2);
          }
          if (sourceRoot != null) {
            sourceFile2 = util.relative(sourceRoot, sourceFile2);
          }
          this.setSourceContent(sourceFile2, content);
        }
      }, this);
    };
    SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
      if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") {
        throw new Error(
          "original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values."
        );
      }
      if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
        return;
      } else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
        return;
      } else {
        throw new Error("Invalid mapping: " + JSON.stringify({
          generated: aGenerated,
          source: aSource,
          original: aOriginal,
          name: aName
        }));
      }
    };
    SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() {
      var previousGeneratedColumn = 0;
      var previousGeneratedLine = 1;
      var previousOriginalColumn = 0;
      var previousOriginalLine = 0;
      var previousName = 0;
      var previousSource = 0;
      var result = "";
      var next;
      var mapping;
      var nameIdx;
      var sourceIdx;
      var mappings = this._mappings.toArray();
      for (var i = 0, len = mappings.length; i < len; i++) {
        mapping = mappings[i];
        next = "";
        if (mapping.generatedLine !== previousGeneratedLine) {
          previousGeneratedColumn = 0;
          while (mapping.generatedLine !== previousGeneratedLine) {
            next += ";";
            previousGeneratedLine++;
          }
        } else {
          if (i > 0) {
            if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
              continue;
            }
            next += ",";
          }
        }
        next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn);
        previousGeneratedColumn = mapping.generatedColumn;
        if (mapping.source != null) {
          sourceIdx = this._sources.indexOf(mapping.source);
          next += base64VLQ.encode(sourceIdx - previousSource);
          previousSource = sourceIdx;
          next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine);
          previousOriginalLine = mapping.originalLine - 1;
          next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn);
          previousOriginalColumn = mapping.originalColumn;
          if (mapping.name != null) {
            nameIdx = this._names.indexOf(mapping.name);
            next += base64VLQ.encode(nameIdx - previousName);
            previousName = nameIdx;
          }
        }
        result += next;
      }
      return result;
    };
    SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
      return aSources.map(function(source) {
        if (!this._sourcesContents) {
          return null;
        }
        if (aSourceRoot != null) {
          source = util.relative(aSourceRoot, source);
        }
        var key = util.toSetString(source);
        return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
      }, this);
    };
    SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
      var map4 = {
        version: this._version,
        sources: this._sources.toArray(),
        names: this._names.toArray(),
        mappings: this._serializeMappings()
      };
      if (this._file != null) {
        map4.file = this._file;
      }
      if (this._sourceRoot != null) {
        map4.sourceRoot = this._sourceRoot;
      }
      if (this._sourcesContents) {
        map4.sourcesContent = this._generateSourcesContent(map4.sources, map4.sourceRoot);
      }
      return map4;
    };
    SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() {
      return JSON.stringify(this.toJSON());
    };
    exports.SourceMapGenerator = SourceMapGenerator;
  }
});

// node_modules/source-map/lib/binary-search.js
var require_binary_search = __commonJS({
  "node_modules/source-map/lib/binary-search.js"(exports) {
    exports.GREATEST_LOWER_BOUND = 1;
    exports.LEAST_UPPER_BOUND = 2;
    function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
      var mid = Math.floor((aHigh - aLow) / 2) + aLow;
      var cmp = aCompare(aNeedle, aHaystack[mid], true);
      if (cmp === 0) {
        return mid;
      } else if (cmp > 0) {
        if (aHigh - mid > 1) {
          return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
        }
        if (aBias == exports.LEAST_UPPER_BOUND) {
          return aHigh < aHaystack.length ? aHigh : -1;
        } else {
          return mid;
        }
      } else {
        if (mid - aLow > 1) {
          return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
        }
        if (aBias == exports.LEAST_UPPER_BOUND) {
          return mid;
        } else {
          return aLow < 0 ? -1 : aLow;
        }
      }
    }
    exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
      if (aHaystack.length === 0) {
        return -1;
      }
      var index = recursiveSearch(
        -1,
        aHaystack.length,
        aNeedle,
        aHaystack,
        aCompare,
        aBias || exports.GREATEST_LOWER_BOUND
      );
      if (index < 0) {
        return -1;
      }
      while (index - 1 >= 0) {
        if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
          break;
        }
        --index;
      }
      return index;
    };
  }
});

// node_modules/source-map/lib/quick-sort.js
var require_quick_sort = __commonJS({
  "node_modules/source-map/lib/quick-sort.js"(exports) {
    function swap(ary, x2, y2) {
      var temp = ary[x2];
      ary[x2] = ary[y2];
      ary[y2] = temp;
    }
    function randomIntInRange(low, high) {
      return Math.round(low + Math.random() * (high - low));
    }
    function doQuickSort(ary, comparator, p, r) {
      if (p < r) {
        var pivotIndex = randomIntInRange(p, r);
        var i = p - 1;
        swap(ary, pivotIndex, r);
        var pivot = ary[r];
        for (var j = p; j < r; j++) {
          if (comparator(ary[j], pivot) <= 0) {
            i += 1;
            swap(ary, i, j);
          }
        }
        swap(ary, i + 1, j);
        var q = i + 1;
        doQuickSort(ary, comparator, p, q - 1);
        doQuickSort(ary, comparator, q + 1, r);
      }
    }
    exports.quickSort = function(ary, comparator) {
      doQuickSort(ary, comparator, 0, ary.length - 1);
    };
  }
});

// node_modules/source-map/lib/source-map-consumer.js
var require_source_map_consumer = __commonJS({
  "node_modules/source-map/lib/source-map-consumer.js"(exports) {
    var util = require_util();
    var binarySearch = require_binary_search();
    var ArraySet = require_array_set().ArraySet;
    var base64VLQ = require_base64_vlq();
    var quickSort = require_quick_sort().quickSort;
    function SourceMapConsumer(aSourceMap, aSourceMapURL) {
      var sourceMap = aSourceMap;
      if (typeof aSourceMap === "string") {
        sourceMap = util.parseSourceMapInput(aSourceMap);
      }
      return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
    }
    SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
      return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
    };
    SourceMapConsumer.prototype._version = 3;
    SourceMapConsumer.prototype.__generatedMappings = null;
    Object.defineProperty(SourceMapConsumer.prototype, "_generatedMappings", {
      configurable: true,
      enumerable: true,
      get: function() {
        if (!this.__generatedMappings) {
          this._parseMappings(this._mappings, this.sourceRoot);
        }
        return this.__generatedMappings;
      }
    });
    SourceMapConsumer.prototype.__originalMappings = null;
    Object.defineProperty(SourceMapConsumer.prototype, "_originalMappings", {
      configurable: true,
      enumerable: true,
      get: function() {
        if (!this.__originalMappings) {
          this._parseMappings(this._mappings, this.sourceRoot);
        }
        return this.__originalMappings;
      }
    });
    SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
      var c = aStr.charAt(index);
      return c === ";" || c === ",";
    };
    SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
      throw new Error("Subclasses must implement _parseMappings");
    };
    SourceMapConsumer.GENERATED_ORDER = 1;
    SourceMapConsumer.ORIGINAL_ORDER = 2;
    SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
    SourceMapConsumer.LEAST_UPPER_BOUND = 2;
    SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
      var context = aContext || null;
      var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
      var mappings;
      switch (order) {
        case SourceMapConsumer.GENERATED_ORDER:
          mappings = this._generatedMappings;
          break;
        case SourceMapConsumer.ORIGINAL_ORDER:
          mappings = this._originalMappings;
          break;
        default:
          throw new Error("Unknown order of iteration.");
      }
      var sourceRoot = this.sourceRoot;
      mappings.map(function(mapping) {
        var source = mapping.source === null ? null : this._sources.at(mapping.source);
        source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
        return {
          source,
          generatedLine: mapping.generatedLine,
          generatedColumn: mapping.generatedColumn,
          originalLine: mapping.originalLine,
          originalColumn: mapping.originalColumn,
          name: mapping.name === null ? null : this._names.at(mapping.name)
        };
      }, this).forEach(aCallback, context);
    };
    SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
      var line = util.getArg(aArgs, "line");
      var needle = {
        source: util.getArg(aArgs, "source"),
        originalLine: line,
        originalColumn: util.getArg(aArgs, "column", 0)
      };
      needle.source = this._findSourceIndex(needle.source);
      if (needle.source < 0) {
        return [];
      }
      var mappings = [];
      var index = this._findMapping(
        needle,
        this._originalMappings,
        "originalLine",
        "originalColumn",
        util.compareByOriginalPositions,
        binarySearch.LEAST_UPPER_BOUND
      );
      if (index >= 0) {
        var mapping = this._originalMappings[index];
        if (aArgs.column === void 0) {
          var originalLine = mapping.originalLine;
          while (mapping && mapping.originalLine === originalLine) {
            mappings.push({
              line: util.getArg(mapping, "generatedLine", null),
              column: util.getArg(mapping, "generatedColumn", null),
              lastColumn: util.getArg(mapping, "lastGeneratedColumn", null)
            });
            mapping = this._originalMappings[++index];
          }
        } else {
          var originalColumn = mapping.originalColumn;
          while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
            mappings.push({
              line: util.getArg(mapping, "generatedLine", null),
              column: util.getArg(mapping, "generatedColumn", null),
              lastColumn: util.getArg(mapping, "lastGeneratedColumn", null)
            });
            mapping = this._originalMappings[++index];
          }
        }
      }
      return mappings;
    };
    exports.SourceMapConsumer = SourceMapConsumer;
    function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
      var sourceMap = aSourceMap;
      if (typeof aSourceMap === "string") {
        sourceMap = util.parseSourceMapInput(aSourceMap);
      }
      var version3 = util.getArg(sourceMap, "version");
      var sources = util.getArg(sourceMap, "sources");
      var names = util.getArg(sourceMap, "names", []);
      var sourceRoot = util.getArg(sourceMap, "sourceRoot", null);
      var sourcesContent = util.getArg(sourceMap, "sourcesContent", null);
      var mappings = util.getArg(sourceMap, "mappings");
      var file2 = util.getArg(sourceMap, "file", null);
      if (version3 != this._version) {
        throw new Error("Unsupported version: " + version3);
      }
      if (sourceRoot) {
        sourceRoot = util.normalize(sourceRoot);
      }
      sources = sources.map(String).map(util.normalize).map(function(source) {
        return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source;
      });
      this._names = ArraySet.fromArray(names.map(String), true);
      this._sources = ArraySet.fromArray(sources, true);
      this._absoluteSources = this._sources.toArray().map(function(s2) {
        return util.computeSourceURL(sourceRoot, s2, aSourceMapURL);
      });
      this.sourceRoot = sourceRoot;
      this.sourcesContent = sourcesContent;
      this._mappings = mappings;
      this._sourceMapURL = aSourceMapURL;
      this.file = file2;
    }
    BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
    BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
    BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
      var relativeSource = aSource;
      if (this.sourceRoot != null) {
        relativeSource = util.relative(this.sourceRoot, relativeSource);
      }
      if (this._sources.has(relativeSource)) {
        return this._sources.indexOf(relativeSource);
      }
      var i;
      for (i = 0; i < this._absoluteSources.length; ++i) {
        if (this._absoluteSources[i] == aSource) {
          return i;
        }
      }
      return -1;
    };
    BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
      var smc = Object.create(BasicSourceMapConsumer.prototype);
      var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
      var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
      smc.sourceRoot = aSourceMap._sourceRoot;
      smc.sourcesContent = aSourceMap._generateSourcesContent(
        smc._sources.toArray(),
        smc.sourceRoot
      );
      smc.file = aSourceMap._file;
      smc._sourceMapURL = aSourceMapURL;
      smc._absoluteSources = smc._sources.toArray().map(function(s2) {
        return util.computeSourceURL(smc.sourceRoot, s2, aSourceMapURL);
      });
      var generatedMappings = aSourceMap._mappings.toArray().slice();
      var destGeneratedMappings = smc.__generatedMappings = [];
      var destOriginalMappings = smc.__originalMappings = [];
      for (var i = 0, length = generatedMappings.length; i < length; i++) {
        var srcMapping = generatedMappings[i];
        var destMapping = new Mapping();
        destMapping.generatedLine = srcMapping.generatedLine;
        destMapping.generatedColumn = srcMapping.generatedColumn;
        if (srcMapping.source) {
          destMapping.source = sources.indexOf(srcMapping.source);
          destMapping.originalLine = srcMapping.originalLine;
          destMapping.originalColumn = srcMapping.originalColumn;
          if (srcMapping.name) {
            destMapping.name = names.indexOf(srcMapping.name);
          }
          destOriginalMappings.push(destMapping);
        }
        destGeneratedMappings.push(destMapping);
      }
      quickSort(smc.__originalMappings, util.compareByOriginalPositions);
      return smc;
    };
    BasicSourceMapConsumer.prototype._version = 3;
    Object.defineProperty(BasicSourceMapConsumer.prototype, "sources", {
      get: function() {
        return this._absoluteSources.slice();
      }
    });
    function Mapping() {
      this.generatedLine = 0;
      this.generatedColumn = 0;
      this.source = null;
      this.originalLine = null;
      this.originalColumn = null;
      this.name = null;
    }
    BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
      var generatedLine = 1;
      var previousGeneratedColumn = 0;
      var previousOriginalLine = 0;
      var previousOriginalColumn = 0;
      var previousSource = 0;
      var previousName = 0;
      var length = aStr.length;
      var index = 0;
      var cachedSegments = {};
      var temp = {};
      var originalMappings = [];
      var generatedMappings = [];
      var mapping, str, segment, end, value;
      while (index < length) {
        if (aStr.charAt(index) === ";") {
          generatedLine++;
          index++;
          previousGeneratedColumn = 0;
        } else if (aStr.charAt(index) === ",") {
          index++;
        } else {
          mapping = new Mapping();
          mapping.generatedLine = generatedLine;
          for (end = index; end < length; end++) {
            if (this._charIsMappingSeparator(aStr, end)) {
              break;
            }
          }
          str = aStr.slice(index, end);
          segment = cachedSegments[str];
          if (segment) {
            index += str.length;
          } else {
            segment = [];
            while (index < end) {
              base64VLQ.decode(aStr, index, temp);
              value = temp.value;
              index = temp.rest;
              segment.push(value);
            }
            if (segment.length === 2) {
              throw new Error("Found a source, but no line and column");
            }
            if (segment.length === 3) {
              throw new Error("Found a source and line, but no column");
            }
            cachedSegments[str] = segment;
          }
          mapping.generatedColumn = previousGeneratedColumn + segment[0];
          previousGeneratedColumn = mapping.generatedColumn;
          if (segment.length > 1) {
            mapping.source = previousSource + segment[1];
            previousSource += segment[1];
            mapping.originalLine = previousOriginalLine + segment[2];
            previousOriginalLine = mapping.originalLine;
            mapping.originalLine += 1;
            mapping.originalColumn = previousOriginalColumn + segment[3];
            previousOriginalColumn = mapping.originalColumn;
            if (segment.length > 4) {
              mapping.name = previousName + segment[4];
              previousName += segment[4];
            }
          }
          generatedMappings.push(mapping);
          if (typeof mapping.originalLine === "number") {
            originalMappings.push(mapping);
          }
        }
      }
      quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
      this.__generatedMappings = generatedMappings;
      quickSort(originalMappings, util.compareByOriginalPositions);
      this.__originalMappings = originalMappings;
    };
    BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
      if (aNeedle[aLineName] <= 0) {
        throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]);
      }
      if (aNeedle[aColumnName] < 0) {
        throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]);
      }
      return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
    };
    BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() {
      for (var index = 0; index < this._generatedMappings.length; ++index) {
        var mapping = this._generatedMappings[index];
        if (index + 1 < this._generatedMappings.length) {
          var nextMapping = this._generatedMappings[index + 1];
          if (mapping.generatedLine === nextMapping.generatedLine) {
            mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
            continue;
          }
        }
        mapping.lastGeneratedColumn = Infinity;
      }
    };
    BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
      var needle = {
        generatedLine: util.getArg(aArgs, "line"),
        generatedColumn: util.getArg(aArgs, "column")
      };
      var index = this._findMapping(
        needle,
        this._generatedMappings,
        "generatedLine",
        "generatedColumn",
        util.compareByGeneratedPositionsDeflated,
        util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)
      );
      if (index >= 0) {
        var mapping = this._generatedMappings[index];
        if (mapping.generatedLine === needle.generatedLine) {
          var source = util.getArg(mapping, "source", null);
          if (source !== null) {
            source = this._sources.at(source);
            source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
          }
          var name = util.getArg(mapping, "name", null);
          if (name !== null) {
            name = this._names.at(name);
          }
          return {
            source,
            line: util.getArg(mapping, "originalLine", null),
            column: util.getArg(mapping, "originalColumn", null),
            name
          };
        }
      }
      return {
        source: null,
        line: null,
        column: null,
        name: null
      };
    };
    BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() {
      if (!this.sourcesContent) {
        return false;
      }
      return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) {
        return sc == null;
      });
    };
    BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
      if (!this.sourcesContent) {
        return null;
      }
      var index = this._findSourceIndex(aSource);
      if (index >= 0) {
        return this.sourcesContent[index];
      }
      var relativeSource = aSource;
      if (this.sourceRoot != null) {
        relativeSource = util.relative(this.sourceRoot, relativeSource);
      }
      var url2;
      if (this.sourceRoot != null && (url2 = util.urlParse(this.sourceRoot))) {
        var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
        if (url2.scheme == "file" && this._sources.has(fileUriAbsPath)) {
          return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
        }
        if ((!url2.path || url2.path == "/") && this._sources.has("/" + relativeSource)) {
          return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
        }
      }
      if (nullOnMissing) {
        return null;
      } else {
        throw new Error('"' + relativeSource + '" is not in the SourceMap.');
      }
    };
    BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
      var source = util.getArg(aArgs, "source");
      source = this._findSourceIndex(source);
      if (source < 0) {
        return {
          line: null,
          column: null,
          lastColumn: null
        };
      }
      var needle = {
        source,
        originalLine: util.getArg(aArgs, "line"),
        originalColumn: util.getArg(aArgs, "column")
      };
      var index = this._findMapping(
        needle,
        this._originalMappings,
        "originalLine",
        "originalColumn",
        util.compareByOriginalPositions,
        util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)
      );
      if (index >= 0) {
        var mapping = this._originalMappings[index];
        if (mapping.source === needle.source) {
          return {
            line: util.getArg(mapping, "generatedLine", null),
            column: util.getArg(mapping, "generatedColumn", null),
            lastColumn: util.getArg(mapping, "lastGeneratedColumn", null)
          };
        }
      }
      return {
        line: null,
        column: null,
        lastColumn: null
      };
    };
    exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
    function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
      var sourceMap = aSourceMap;
      if (typeof aSourceMap === "string") {
        sourceMap = util.parseSourceMapInput(aSourceMap);
      }
      var version3 = util.getArg(sourceMap, "version");
      var sections = util.getArg(sourceMap, "sections");
      if (version3 != this._version) {
        throw new Error("Unsupported version: " + version3);
      }
      this._sources = new ArraySet();
      this._names = new ArraySet();
      var lastOffset = {
        line: -1,
        column: 0
      };
      this._sections = sections.map(function(s2) {
        if (s2.url) {
          throw new Error("Support for url field in sections not implemented.");
        }
        var offset2 = util.getArg(s2, "offset");
        var offsetLine = util.getArg(offset2, "line");
        var offsetColumn = util.getArg(offset2, "column");
        if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
          throw new Error("Section offsets must be ordered and non-overlapping.");
        }
        lastOffset = offset2;
        return {
          generatedOffset: {
            // The offset fields are 0-based, but we use 1-based indices when
            // encoding/decoding from VLQ.
            generatedLine: offsetLine + 1,
            generatedColumn: offsetColumn + 1
          },
          consumer: new SourceMapConsumer(util.getArg(s2, "map"), aSourceMapURL)
        };
      });
    }
    IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
    IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
    IndexedSourceMapConsumer.prototype._version = 3;
    Object.defineProperty(IndexedSourceMapConsumer.prototype, "sources", {
      get: function() {
        var sources = [];
        for (var i = 0; i < this._sections.length; i++) {
          for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
            sources.push(this._sections[i].consumer.sources[j]);
          }
        }
        return sources;
      }
    });
    IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
      var needle = {
        generatedLine: util.getArg(aArgs, "line"),
        generatedColumn: util.getArg(aArgs, "column")
      };
      var sectionIndex = binarySearch.search(
        needle,
        this._sections,
        function(needle2, section2) {
          var cmp = needle2.generatedLine - section2.generatedOffset.generatedLine;
          if (cmp) {
            return cmp;
          }
          return needle2.generatedColumn - section2.generatedOffset.generatedColumn;
        }
      );
      var section = this._sections[sectionIndex];
      if (!section) {
        return {
          source: null,
          line: null,
          column: null,
          name: null
        };
      }
      return section.consumer.originalPositionFor({
        line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
        column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
        bias: aArgs.bias
      });
    };
    IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() {
      return this._sections.every(function(s2) {
        return s2.consumer.hasContentsOfAllSources();
      });
    };
    IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
      for (var i = 0; i < this._sections.length; i++) {
        var section = this._sections[i];
        var content = section.consumer.sourceContentFor(aSource, true);
        if (content) {
          return content;
        }
      }
      if (nullOnMissing) {
        return null;
      } else {
        throw new Error('"' + aSource + '" is not in the SourceMap.');
      }
    };
    IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
      for (var i = 0; i < this._sections.length; i++) {
        var section = this._sections[i];
        if (section.consumer._findSourceIndex(util.getArg(aArgs, "source")) === -1) {
          continue;
        }
        var generatedPosition = section.consumer.generatedPositionFor(aArgs);
        if (generatedPosition) {
          var ret = {
            line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
            column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
          };
          return ret;
        }
      }
      return {
        line: null,
        column: null
      };
    };
    IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
      this.__generatedMappings = [];
      this.__originalMappings = [];
      for (var i = 0; i < this._sections.length; i++) {
        var section = this._sections[i];
        var sectionMappings = section.consumer._generatedMappings;
        for (var j = 0; j < sectionMappings.length; j++) {
          var mapping = sectionMappings[j];
          var source = section.consumer._sources.at(mapping.source);
          source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
          this._sources.add(source);
          source = this._sources.indexOf(source);
          var name = null;
          if (mapping.name) {
            name = section.consumer._names.at(mapping.name);
            this._names.add(name);
            name = this._names.indexOf(name);
          }
          var adjustedMapping = {
            source,
            generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
            generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
            originalLine: mapping.originalLine,
            originalColumn: mapping.originalColumn,
            name
          };
          this.__generatedMappings.push(adjustedMapping);
          if (typeof adjustedMapping.originalLine === "number") {
            this.__originalMappings.push(adjustedMapping);
          }
        }
      }
      quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
      quickSort(this.__originalMappings, util.compareByOriginalPositions);
    };
    exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  }
});

// node_modules/source-map/lib/source-node.js
var require_source_node = __commonJS({
  "node_modules/source-map/lib/source-node.js"(exports) {
    var SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
    var util = require_util();
    var REGEX_NEWLINE = /(\r?\n)/;
    var NEWLINE_CODE = 10;
    var isSourceNode = "$$$isSourceNode$$$";
    function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
      this.children = [];
      this.sourceContents = {};
      this.line = aLine == null ? null : aLine;
      this.column = aColumn == null ? null : aColumn;
      this.source = aSource == null ? null : aSource;
      this.name = aName == null ? null : aName;
      this[isSourceNode] = true;
      if (aChunks != null) this.add(aChunks);
    }
    SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
      var node = new SourceNode();
      var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
      var remainingLinesIndex = 0;
      var shiftNextLine = function() {
        var lineContents = getNextLine();
        var newLine = getNextLine() || "";
        return lineContents + newLine;
        function getNextLine() {
          return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0;
        }
      };
      var lastGeneratedLine = 1, lastGeneratedColumn = 0;
      var lastMapping = null;
      aSourceMapConsumer.eachMapping(function(mapping) {
        if (lastMapping !== null) {
          if (lastGeneratedLine < mapping.generatedLine) {
            addMappingWithCode(lastMapping, shiftNextLine());
            lastGeneratedLine++;
            lastGeneratedColumn = 0;
          } else {
            var nextLine = remainingLines[remainingLinesIndex] || "";
            var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
            remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
            lastGeneratedColumn = mapping.generatedColumn;
            addMappingWithCode(lastMapping, code);
            lastMapping = mapping;
            return;
          }
        }
        while (lastGeneratedLine < mapping.generatedLine) {
          node.add(shiftNextLine());
          lastGeneratedLine++;
        }
        if (lastGeneratedColumn < mapping.generatedColumn) {
          var nextLine = remainingLines[remainingLinesIndex] || "";
          node.add(nextLine.substr(0, mapping.generatedColumn));
          remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
          lastGeneratedColumn = mapping.generatedColumn;
        }
        lastMapping = mapping;
      }, this);
      if (remainingLinesIndex < remainingLines.length) {
        if (lastMapping) {
          addMappingWithCode(lastMapping, shiftNextLine());
        }
        node.add(remainingLines.splice(remainingLinesIndex).join(""));
      }
      aSourceMapConsumer.sources.forEach(function(sourceFile) {
        var content = aSourceMapConsumer.sourceContentFor(sourceFile);
        if (content != null) {
          if (aRelativePath != null) {
            sourceFile = util.join(aRelativePath, sourceFile);
          }
          node.setSourceContent(sourceFile, content);
        }
      });
      return node;
      function addMappingWithCode(mapping, code) {
        if (mapping === null || mapping.source === void 0) {
          node.add(code);
        } else {
          var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source;
          node.add(new SourceNode(
            mapping.originalLine,
            mapping.originalColumn,
            source,
            code,
            mapping.name
          ));
        }
      }
    };
    SourceNode.prototype.add = function SourceNode_add(aChunk) {
      if (Array.isArray(aChunk)) {
        aChunk.forEach(function(chunk) {
          this.add(chunk);
        }, this);
      } else if (aChunk[isSourceNode] || typeof aChunk === "string") {
        if (aChunk) {
          this.children.push(aChunk);
        }
      } else {
        throw new TypeError(
          "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
        );
      }
      return this;
    };
    SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
      if (Array.isArray(aChunk)) {
        for (var i = aChunk.length - 1; i >= 0; i--) {
          this.prepend(aChunk[i]);
        }
      } else if (aChunk[isSourceNode] || typeof aChunk === "string") {
        this.children.unshift(aChunk);
      } else {
        throw new TypeError(
          "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
        );
      }
      return this;
    };
    SourceNode.prototype.walk = function SourceNode_walk(aFn) {
      var chunk;
      for (var i = 0, len = this.children.length; i < len; i++) {
        chunk = this.children[i];
        if (chunk[isSourceNode]) {
          chunk.walk(aFn);
        } else {
          if (chunk !== "") {
            aFn(chunk, {
              source: this.source,
              line: this.line,
              column: this.column,
              name: this.name
            });
          }
        }
      }
    };
    SourceNode.prototype.join = function SourceNode_join(aSep) {
      var newChildren;
      var i;
      var len = this.children.length;
      if (len > 0) {
        newChildren = [];
        for (i = 0; i < len - 1; i++) {
          newChildren.push(this.children[i]);
          newChildren.push(aSep);
        }
        newChildren.push(this.children[i]);
        this.children = newChildren;
      }
      return this;
    };
    SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
      var lastChild = this.children[this.children.length - 1];
      if (lastChild[isSourceNode]) {
        lastChild.replaceRight(aPattern, aReplacement);
      } else if (typeof lastChild === "string") {
        this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
      } else {
        this.children.push("".replace(aPattern, aReplacement));
      }
      return this;
    };
    SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
      this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
    };
    SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) {
      for (var i = 0, len = this.children.length; i < len; i++) {
        if (this.children[i][isSourceNode]) {
          this.children[i].walkSourceContents(aFn);
        }
      }
      var sources = Object.keys(this.sourceContents);
      for (var i = 0, len = sources.length; i < len; i++) {
        aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
      }
    };
    SourceNode.prototype.toString = function SourceNode_toString() {
      var str = "";
      this.walk(function(chunk) {
        str += chunk;
      });
      return str;
    };
    SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
      var generated = {
        code: "",
        line: 1,
        column: 0
      };
      var map4 = new SourceMapGenerator(aArgs);
      var sourceMappingActive = false;
      var lastOriginalSource = null;
      var lastOriginalLine = null;
      var lastOriginalColumn = null;
      var lastOriginalName = null;
      this.walk(function(chunk, original) {
        generated.code += chunk;
        if (original.source !== null && original.line !== null && original.column !== null) {
          if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
            map4.addMapping({
              source: original.source,
              original: {
                line: original.line,
                column: original.column
              },
              generated: {
                line: generated.line,
                column: generated.column
              },
              name: original.name
            });
          }
          lastOriginalSource = original.source;
          lastOriginalLine = original.line;
          lastOriginalColumn = original.column;
          lastOriginalName = original.name;
          sourceMappingActive = true;
        } else if (sourceMappingActive) {
          map4.addMapping({
            generated: {
              line: generated.line,
              column: generated.column
            }
          });
          lastOriginalSource = null;
          sourceMappingActive = false;
        }
        for (var idx = 0, length = chunk.length; idx < length; idx++) {
          if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
            generated.line++;
            generated.column = 0;
            if (idx + 1 === length) {
              lastOriginalSource = null;
              sourceMappingActive = false;
            } else if (sourceMappingActive) {
              map4.addMapping({
                source: original.source,
                original: {
                  line: original.line,
                  column: original.column
                },
                generated: {
                  line: generated.line,
                  column: generated.column
                },
                name: original.name
              });
            }
          } else {
            generated.column++;
          }
        }
      });
      this.walkSourceContents(function(sourceFile, sourceContent) {
        map4.setSourceContent(sourceFile, sourceContent);
      });
      return { code: generated.code, map: map4 };
    };
    exports.SourceNode = SourceNode;
  }
});

// node_modules/source-map/source-map.js
var require_source_map = __commonJS({
  "node_modules/source-map/source-map.js"(exports) {
    exports.SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
    exports.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer;
    exports.SourceNode = require_source_node().SourceNode;
  }
});

// node_modules/handlebars/dist/cjs/handlebars/compiler/code-gen.js
var require_code_gen = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/compiler/code-gen.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    var _utils = require_utils();
    var SourceNode = void 0;
    try {
      if (typeof define !== "function" || !define.amd) {
        SourceMap = require_source_map();
        SourceNode = SourceMap.SourceNode;
      }
    } catch (err) {
    }
    var SourceMap;
    if (!SourceNode) {
      SourceNode = function(line, column, srcFile, chunks) {
        this.src = "";
        if (chunks) {
          this.add(chunks);
        }
      };
      SourceNode.prototype = {
        add: function add2(chunks) {
          if (_utils.isArray(chunks)) {
            chunks = chunks.join("");
          }
          this.src += chunks;
        },
        prepend: function prepend(chunks) {
          if (_utils.isArray(chunks)) {
            chunks = chunks.join("");
          }
          this.src = chunks + this.src;
        },
        toStringWithSourceMap: function toStringWithSourceMap() {
          return { code: this.toString() };
        },
        toString: function toString() {
          return this.src;
        }
      };
    }
    function castChunk(chunk, codeGen, loc) {
      if (_utils.isArray(chunk)) {
        var ret = [];
        for (var i = 0, len = chunk.length; i < len; i++) {
          ret.push(codeGen.wrap(chunk[i], loc));
        }
        return ret;
      } else if (typeof chunk === "boolean" || typeof chunk === "number") {
        return chunk + "";
      }
      return chunk;
    }
    function CodeGen(srcFile) {
      this.srcFile = srcFile;
      this.source = [];
    }
    CodeGen.prototype = {
      isEmpty: function isEmpty() {
        return !this.source.length;
      },
      prepend: function prepend(source, loc) {
        this.source.unshift(this.wrap(source, loc));
      },
      push: function push(source, loc) {
        this.source.push(this.wrap(source, loc));
      },
      merge: function merge4() {
        var source = this.empty();
        this.each(function(line) {
          source.add(["  ", line, "\n"]);
        });
        return source;
      },
      each: function each(iter) {
        for (var i = 0, len = this.source.length; i < len; i++) {
          iter(this.source[i]);
        }
      },
      empty: function empty2() {
        var loc = this.currentLocation || { start: {} };
        return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
      },
      wrap: function wrap(chunk) {
        var loc = arguments.length <= 1 || arguments[1] === void 0 ? this.currentLocation || { start: {} } : arguments[1];
        if (chunk instanceof SourceNode) {
          return chunk;
        }
        chunk = castChunk(chunk, this, loc);
        return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
      },
      functionCall: function functionCall(fn, type, params) {
        params = this.generateList(params);
        return this.wrap([fn, type ? "." + type + "(" : "(", params, ")"]);
      },
      quotedString: function quotedString(str) {
        return '"' + (str + "").replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029") + '"';
      },
      objectLiteral: function objectLiteral(obj) {
        var _this = this;
        var pairs = [];
        Object.keys(obj).forEach(function(key) {
          var value = castChunk(obj[key], _this);
          if (value !== "undefined") {
            pairs.push([_this.quotedString(key), ":", value]);
          }
        });
        var ret = this.generateList(pairs);
        ret.prepend("{");
        ret.add("}");
        return ret;
      },
      generateList: function generateList(entries) {
        var ret = this.empty();
        for (var i = 0, len = entries.length; i < len; i++) {
          if (i) {
            ret.add(",");
          }
          ret.add(castChunk(entries[i], this));
        }
        return ret;
      },
      generateArray: function generateArray(entries) {
        var ret = this.generateList(entries);
        ret.prepend("[");
        ret.add("]");
        return ret;
      }
    };
    exports["default"] = CodeGen;
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js
var require_javascript_compiler = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _base = require_base();
    var _exception = require_exception();
    var _exception2 = _interopRequireDefault(_exception);
    var _utils = require_utils();
    var _codeGen = require_code_gen();
    var _codeGen2 = _interopRequireDefault(_codeGen);
    function Literal(value) {
      this.value = value;
    }
    function JavaScriptCompiler() {
    }
    JavaScriptCompiler.prototype = {
      // PUBLIC API: You can override these methods in a subclass to provide
      // alternative compiled forms for name lookup and buffering semantics
      nameLookup: function nameLookup(parent, name) {
        return this.internalNameLookup(parent, name);
      },
      depthedLookup: function depthedLookup(name) {
        return [this.aliasable("container.lookup"), "(depths, ", JSON.stringify(name), ")"];
      },
      compilerInfo: function compilerInfo() {
        var revision = _base.COMPILER_REVISION, versions = _base.REVISION_CHANGES[revision];
        return [revision, versions];
      },
      appendToBuffer: function appendToBuffer(source, location, explicit) {
        if (!_utils.isArray(source)) {
          source = [source];
        }
        source = this.source.wrap(source, location);
        if (this.environment.isSimple) {
          return ["return ", source, ";"];
        } else if (explicit) {
          return ["buffer += ", source, ";"];
        } else {
          source.appendToBuffer = true;
          return source;
        }
      },
      initializeBuffer: function initializeBuffer() {
        return this.quotedString("");
      },
      // END PUBLIC API
      internalNameLookup: function internalNameLookup(parent, name) {
        this.lookupPropertyFunctionIsUsed = true;
        return ["lookupProperty(", parent, ",", JSON.stringify(name), ")"];
      },
      lookupPropertyFunctionIsUsed: false,
      compile: function compile(environment, options, context, asObject) {
        this.environment = environment;
        this.options = options;
        this.stringParams = this.options.stringParams;
        this.trackIds = this.options.trackIds;
        this.precompile = !asObject;
        this.name = this.environment.name;
        this.isChild = !!context;
        this.context = context || {
          decorators: [],
          programs: [],
          environments: []
        };
        this.preamble();
        this.stackSlot = 0;
        this.stackVars = [];
        this.aliases = {};
        this.registers = { list: [] };
        this.hashes = [];
        this.compileStack = [];
        this.inlineStack = [];
        this.blockParams = [];
        this.compileChildren(environment, options);
        this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
        this.useBlockParams = this.useBlockParams || environment.useBlockParams;
        var opcodes = environment.opcodes, opcode = void 0, firstLoc = void 0, i = void 0, l2 = void 0;
        for (i = 0, l2 = opcodes.length; i < l2; i++) {
          opcode = opcodes[i];
          this.source.currentLocation = opcode.loc;
          firstLoc = firstLoc || opcode.loc;
          this[opcode.opcode].apply(this, opcode.args);
        }
        this.source.currentLocation = firstLoc;
        this.pushSource("");
        if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
          throw new _exception2["default"]("Compile completed with content left on stack");
        }
        if (!this.decorators.isEmpty()) {
          this.useDecorators = true;
          this.decorators.prepend(["var decorators = container.decorators, ", this.lookupPropertyFunctionVarDeclaration(), ";\n"]);
          this.decorators.push("return fn;");
          if (asObject) {
            this.decorators = Function.apply(this, ["fn", "props", "container", "depth0", "data", "blockParams", "depths", this.decorators.merge()]);
          } else {
            this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n");
            this.decorators.push("}\n");
            this.decorators = this.decorators.merge();
          }
        } else {
          this.decorators = void 0;
        }
        var fn = this.createFunctionContext(asObject);
        if (!this.isChild) {
          var ret = {
            compiler: this.compilerInfo(),
            main: fn
          };
          if (this.decorators) {
            ret.main_d = this.decorators;
            ret.useDecorators = true;
          }
          var _context = this.context;
          var programs = _context.programs;
          var decorators = _context.decorators;
          for (i = 0, l2 = programs.length; i < l2; i++) {
            ret[i] = programs[i];
            if (decorators[i]) {
              ret[i + "_d"] = decorators[i];
              ret.useDecorators = true;
            }
          }
          if (this.environment.usePartial) {
            ret.usePartial = true;
          }
          if (this.options.data) {
            ret.useData = true;
          }
          if (this.useDepths) {
            ret.useDepths = true;
          }
          if (this.useBlockParams) {
            ret.useBlockParams = true;
          }
          if (this.options.compat) {
            ret.compat = true;
          }
          if (!asObject) {
            ret.compiler = JSON.stringify(ret.compiler);
            this.source.currentLocation = { start: { line: 1, column: 0 } };
            ret = this.objectLiteral(ret);
            if (options.srcName) {
              ret = ret.toStringWithSourceMap({ file: options.destName });
              ret.map = ret.map && ret.map.toString();
            } else {
              ret = ret.toString();
            }
          } else {
            ret.compilerOptions = this.options;
          }
          return ret;
        } else {
          return fn;
        }
      },
      preamble: function preamble() {
        this.lastContext = 0;
        this.source = new _codeGen2["default"](this.options.srcName);
        this.decorators = new _codeGen2["default"](this.options.srcName);
      },
      createFunctionContext: function createFunctionContext(asObject) {
        var _this = this;
        var varDeclarations = "";
        var locals = this.stackVars.concat(this.registers.list);
        if (locals.length > 0) {
          varDeclarations += ", " + locals.join(", ");
        }
        var aliasCount = 0;
        Object.keys(this.aliases).forEach(function(alias) {
          var node = _this.aliases[alias];
          if (node.children && node.referenceCount > 1) {
            varDeclarations += ", alias" + ++aliasCount + "=" + alias;
            node.children[0] = "alias" + aliasCount;
          }
        });
        if (this.lookupPropertyFunctionIsUsed) {
          varDeclarations += ", " + this.lookupPropertyFunctionVarDeclaration();
        }
        var params = ["container", "depth0", "helpers", "partials", "data"];
        if (this.useBlockParams || this.useDepths) {
          params.push("blockParams");
        }
        if (this.useDepths) {
          params.push("depths");
        }
        var source = this.mergeSource(varDeclarations);
        if (asObject) {
          params.push(source);
          return Function.apply(this, params);
        } else {
          return this.source.wrap(["function(", params.join(","), ") {\n  ", source, "}"]);
        }
      },
      mergeSource: function mergeSource(varDeclarations) {
        var isSimple = this.environment.isSimple, appendOnly = !this.forceBuffer, appendFirst = void 0, sourceSeen = void 0, bufferStart = void 0, bufferEnd = void 0;
        this.source.each(function(line) {
          if (line.appendToBuffer) {
            if (bufferStart) {
              line.prepend("  + ");
            } else {
              bufferStart = line;
            }
            bufferEnd = line;
          } else {
            if (bufferStart) {
              if (!sourceSeen) {
                appendFirst = true;
              } else {
                bufferStart.prepend("buffer += ");
              }
              bufferEnd.add(";");
              bufferStart = bufferEnd = void 0;
            }
            sourceSeen = true;
            if (!isSimple) {
              appendOnly = false;
            }
          }
        });
        if (appendOnly) {
          if (bufferStart) {
            bufferStart.prepend("return ");
            bufferEnd.add(";");
          } else if (!sourceSeen) {
            this.source.push('return "";');
          }
        } else {
          varDeclarations += ", buffer = " + (appendFirst ? "" : this.initializeBuffer());
          if (bufferStart) {
            bufferStart.prepend("return buffer + ");
            bufferEnd.add(";");
          } else {
            this.source.push("return buffer;");
          }
        }
        if (varDeclarations) {
          this.source.prepend("var " + varDeclarations.substring(2) + (appendFirst ? "" : ";\n"));
        }
        return this.source.merge();
      },
      lookupPropertyFunctionVarDeclaration: function lookupPropertyFunctionVarDeclaration() {
        return "\n      lookupProperty = container.lookupProperty || function(parent, propertyName) {\n        if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {\n          return parent[propertyName];\n        }\n        return undefined\n    }\n    ".trim();
      },
      // [blockValue]
      //
      // On stack, before: hash, inverse, program, value
      // On stack, after: return value of blockHelperMissing
      //
      // The purpose of this opcode is to take a block of the form
      // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
      // replace it on the stack with the result of properly
      // invoking blockHelperMissing.
      blockValue: function blockValue(name) {
        var blockHelperMissing = this.aliasable("container.hooks.blockHelperMissing"), params = [this.contextName(0)];
        this.setupHelperArgs(name, 0, params);
        var blockName = this.popStack();
        params.splice(1, 0, blockName);
        this.push(this.source.functionCall(blockHelperMissing, "call", params));
      },
      // [ambiguousBlockValue]
      //
      // On stack, before: hash, inverse, program, value
      // Compiler value, before: lastHelper=value of last found helper, if any
      // On stack, after, if no lastHelper: same as [blockValue]
      // On stack, after, if lastHelper: value
      ambiguousBlockValue: function ambiguousBlockValue() {
        var blockHelperMissing = this.aliasable("container.hooks.blockHelperMissing"), params = [this.contextName(0)];
        this.setupHelperArgs("", 0, params, true);
        this.flushInline();
        var current = this.topStack();
        params.splice(1, 0, current);
        this.pushSource(["if (!", this.lastHelper, ") { ", current, " = ", this.source.functionCall(blockHelperMissing, "call", params), "}"]);
      },
      // [appendContent]
      //
      // On stack, before: ...
      // On stack, after: ...
      //
      // Appends the string value of `content` to the current buffer
      appendContent: function appendContent(content) {
        if (this.pendingContent) {
          content = this.pendingContent + content;
        } else {
          this.pendingLocation = this.source.currentLocation;
        }
        this.pendingContent = content;
      },
      // [append]
      //
      // On stack, before: value, ...
      // On stack, after: ...
      //
      // Coerces `value` to a String and appends it to the current buffer.
      //
      // If `value` is truthy, or 0, it is coerced into a string and appended
      // Otherwise, the empty string is appended
      append: function append2() {
        if (this.isInline()) {
          this.replaceStack(function(current) {
            return [" != null ? ", current, ' : ""'];
          });
          this.pushSource(this.appendToBuffer(this.popStack()));
        } else {
          var local = this.popStack();
          this.pushSource(["if (", local, " != null) { ", this.appendToBuffer(local, void 0, true), " }"]);
          if (this.environment.isSimple) {
            this.pushSource(["else { ", this.appendToBuffer("''", void 0, true), " }"]);
          }
        }
      },
      // [appendEscaped]
      //
      // On stack, before: value, ...
      // On stack, after: ...
      //
      // Escape `value` and append it to the buffer
      appendEscaped: function appendEscaped() {
        this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"), "(", this.popStack(), ")"]));
      },
      // [getContext]
      //
      // On stack, before: ...
      // On stack, after: ...
      // Compiler value, after: lastContext=depth
      //
      // Set the value of the `lastContext` compiler value to the depth
      getContext: function getContext(depth) {
        this.lastContext = depth;
      },
      // [pushContext]
      //
      // On stack, before: ...
      // On stack, after: currentContext, ...
      //
      // Pushes the value of the current context onto the stack.
      pushContext: function pushContext() {
        this.pushStackLiteral(this.contextName(this.lastContext));
      },
      // [lookupOnContext]
      //
      // On stack, before: ...
      // On stack, after: currentContext[name], ...
      //
      // Looks up the value of `name` on the current context and pushes
      // it onto the stack.
      lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
        var i = 0;
        if (!scoped && this.options.compat && !this.lastContext) {
          this.push(this.depthedLookup(parts[i++]));
        } else {
          this.pushContext();
        }
        this.resolvePath("context", parts, i, falsy, strict);
      },
      // [lookupBlockParam]
      //
      // On stack, before: ...
      // On stack, after: blockParam[name], ...
      //
      // Looks up the value of `parts` on the given block param and pushes
      // it onto the stack.
      lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
        this.useBlockParams = true;
        this.push(["blockParams[", blockParamId[0], "][", blockParamId[1], "]"]);
        this.resolvePath("context", parts, 1);
      },
      // [lookupData]
      //
      // On stack, before: ...
      // On stack, after: data, ...
      //
      // Push the data lookup operator
      lookupData: function lookupData(depth, parts, strict) {
        if (!depth) {
          this.pushStackLiteral("data");
        } else {
          this.pushStackLiteral("container.data(data, " + depth + ")");
        }
        this.resolvePath("data", parts, 0, true, strict);
      },
      resolvePath: function resolvePath(type, parts, startPartIndex, falsy, strict) {
        var _this2 = this;
        if (this.options.strict || this.options.assumeObjects) {
          this.push(strictLookup(this.options.strict && strict, this, parts, startPartIndex, type));
          return;
        }
        var len = parts.length;
        var _loop = function(i2) {
          _this2.replaceStack(function(current) {
            var lookup = _this2.nameLookup(current, parts[i2], type);
            if (!falsy) {
              return [" != null ? ", lookup, " : ", current];
            } else {
              return [" && ", lookup];
            }
          });
        };
        for (var i = startPartIndex; i < len; i++) {
          _loop(i);
        }
      },
      // [resolvePossibleLambda]
      //
      // On stack, before: value, ...
      // On stack, after: resolved value, ...
      //
      // If the `value` is a lambda, replace it on the stack by
      // the return value of the lambda
      resolvePossibleLambda: function resolvePossibleLambda() {
        this.push([this.aliasable("container.lambda"), "(", this.popStack(), ", ", this.contextName(0), ")"]);
      },
      // [pushStringParam]
      //
      // On stack, before: ...
      // On stack, after: string, currentContext, ...
      //
      // This opcode is designed for use in string mode, which
      // provides the string value of a parameter along with its
      // depth rather than resolving it immediately.
      pushStringParam: function pushStringParam(string4, type) {
        this.pushContext();
        this.pushString(type);
        if (type !== "SubExpression") {
          if (typeof string4 === "string") {
            this.pushString(string4);
          } else {
            this.pushStackLiteral(string4);
          }
        }
      },
      emptyHash: function emptyHash(omitEmpty) {
        if (this.trackIds) {
          this.push("{}");
        }
        if (this.stringParams) {
          this.push("{}");
          this.push("{}");
        }
        this.pushStackLiteral(omitEmpty ? "undefined" : "{}");
      },
      pushHash: function pushHash() {
        if (this.hash) {
          this.hashes.push(this.hash);
        }
        this.hash = { values: {}, types: [], contexts: [], ids: [] };
      },
      popHash: function popHash() {
        var hash2 = this.hash;
        this.hash = this.hashes.pop();
        if (this.trackIds) {
          this.push(this.objectLiteral(hash2.ids));
        }
        if (this.stringParams) {
          this.push(this.objectLiteral(hash2.contexts));
          this.push(this.objectLiteral(hash2.types));
        }
        this.push(this.objectLiteral(hash2.values));
      },
      // [pushString]
      //
      // On stack, before: ...
      // On stack, after: quotedString(string), ...
      //
      // Push a quoted version of `string` onto the stack
      pushString: function pushString(string4) {
        this.pushStackLiteral(this.quotedString(string4));
      },
      // [pushLiteral]
      //
      // On stack, before: ...
      // On stack, after: value, ...
      //
      // Pushes a value onto the stack. This operation prevents
      // the compiler from creating a temporary variable to hold
      // it.
      pushLiteral: function pushLiteral(value) {
        this.pushStackLiteral(value);
      },
      // [pushProgram]
      //
      // On stack, before: ...
      // On stack, after: program(guid), ...
      //
      // Push a program expression onto the stack. This takes
      // a compile-time guid and converts it into a runtime-accessible
      // expression.
      pushProgram: function pushProgram(guid3) {
        if (guid3 != null) {
          this.pushStackLiteral(this.programExpression(guid3));
        } else {
          this.pushStackLiteral(null);
        }
      },
      // [registerDecorator]
      //
      // On stack, before: hash, program, params..., ...
      // On stack, after: ...
      //
      // Pops off the decorator's parameters, invokes the decorator,
      // and inserts the decorator into the decorators list.
      registerDecorator: function registerDecorator(paramSize, name) {
        var foundDecorator = this.nameLookup("decorators", name, "decorator"), options = this.setupHelperArgs(name, paramSize);
        this.decorators.push(["var decorator = ", foundDecorator, ";"]);
        this.decorators.push(['if (typeof decorator !== "function") { throw new Error(', this.quotedString('Missing decorator: "' + name + '"'), "); }"]);
        this.decorators.push(["fn = ", this.decorators.functionCall("decorator", "", ["fn", "props", "container", options]), " || fn;"]);
      },
      // [invokeHelper]
      //
      // On stack, before: hash, inverse, program, params..., ...
      // On stack, after: result of helper invocation
      //
      // Pops off the helper's parameters, invokes the helper,
      // and pushes the helper's return value onto the stack.
      //
      // If the helper is not found, `helperMissing` is called.
      invokeHelper: function invokeHelper(paramSize, name, isSimple) {
        var nonHelper = this.popStack(), helper = this.setupHelper(paramSize, name);
        var possibleFunctionCalls = [];
        if (isSimple) {
          possibleFunctionCalls.push(helper.name);
        }
        possibleFunctionCalls.push(nonHelper);
        if (!this.options.strict) {
          possibleFunctionCalls.push(this.aliasable("container.hooks.helperMissing"));
        }
        var functionLookupCode = ["(", this.itemsSeparatedBy(possibleFunctionCalls, "||"), ")"];
        var functionCall = this.source.functionCall(functionLookupCode, "call", helper.callParams);
        this.push(functionCall);
      },
      itemsSeparatedBy: function itemsSeparatedBy(items, separator) {
        var result = [];
        result.push(items[0]);
        for (var i = 1; i < items.length; i++) {
          result.push(separator, items[i]);
        }
        return result;
      },
      // [invokeKnownHelper]
      //
      // On stack, before: hash, inverse, program, params..., ...
      // On stack, after: result of helper invocation
      //
      // This operation is used when the helper is known to exist,
      // so a `helperMissing` fallback is not required.
      invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
        var helper = this.setupHelper(paramSize, name);
        this.push(this.source.functionCall(helper.name, "call", helper.callParams));
      },
      // [invokeAmbiguous]
      //
      // On stack, before: hash, inverse, program, params..., ...
      // On stack, after: result of disambiguation
      //
      // This operation is used when an expression like `{{foo}}`
      // is provided, but we don't know at compile-time whether it
      // is a helper or a path.
      //
      // This operation emits more code than the other options,
      // and can be avoided by passing the `knownHelpers` and
      // `knownHelpersOnly` flags at compile-time.
      invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
        this.useRegister("helper");
        var nonHelper = this.popStack();
        this.emptyHash();
        var helper = this.setupHelper(0, name, helperCall);
        var helperName = this.lastHelper = this.nameLookup("helpers", name, "helper");
        var lookup = ["(", "(helper = ", helperName, " || ", nonHelper, ")"];
        if (!this.options.strict) {
          lookup[0] = "(helper = ";
          lookup.push(" != null ? helper : ", this.aliasable("container.hooks.helperMissing"));
        }
        this.push(["(", lookup, helper.paramsInit ? ["),(", helper.paramsInit] : [], "),", "(typeof helper === ", this.aliasable('"function"'), " ? ", this.source.functionCall("helper", "call", helper.callParams), " : helper))"]);
      },
      // [invokePartial]
      //
      // On stack, before: context, ...
      // On stack after: result of partial invocation
      //
      // This operation pops off a context, invokes a partial with that context,
      // and pushes the result of the invocation back.
      invokePartial: function invokePartial(isDynamic, name, indent) {
        var params = [], options = this.setupParams(name, 1, params);
        if (isDynamic) {
          name = this.popStack();
          delete options.name;
        }
        if (indent) {
          options.indent = JSON.stringify(indent);
        }
        options.helpers = "helpers";
        options.partials = "partials";
        options.decorators = "container.decorators";
        if (!isDynamic) {
          params.unshift(this.nameLookup("partials", name, "partial"));
        } else {
          params.unshift(name);
        }
        if (this.options.compat) {
          options.depths = "depths";
        }
        options = this.objectLiteral(options);
        params.push(options);
        this.push(this.source.functionCall("container.invokePartial", "", params));
      },
      // [assignToHash]
      //
      // On stack, before: value, ..., hash, ...
      // On stack, after: ..., hash, ...
      //
      // Pops a value off the stack and assigns it to the current hash
      assignToHash: function assignToHash(key) {
        var value = this.popStack(), context = void 0, type = void 0, id2 = void 0;
        if (this.trackIds) {
          id2 = this.popStack();
        }
        if (this.stringParams) {
          type = this.popStack();
          context = this.popStack();
        }
        var hash2 = this.hash;
        if (context) {
          hash2.contexts[key] = context;
        }
        if (type) {
          hash2.types[key] = type;
        }
        if (id2) {
          hash2.ids[key] = id2;
        }
        hash2.values[key] = value;
      },
      pushId: function pushId(type, name, child) {
        if (type === "BlockParam") {
          this.pushStackLiteral("blockParams[" + name[0] + "].path[" + name[1] + "]" + (child ? " + " + JSON.stringify("." + child) : ""));
        } else if (type === "PathExpression") {
          this.pushString(name);
        } else if (type === "SubExpression") {
          this.pushStackLiteral("true");
        } else {
          this.pushStackLiteral("null");
        }
      },
      // HELPERS
      compiler: JavaScriptCompiler,
      compileChildren: function compileChildren(environment, options) {
        var children2 = environment.children, child = void 0, compiler = void 0;
        for (var i = 0, l2 = children2.length; i < l2; i++) {
          child = children2[i];
          compiler = new this.compiler();
          var existing = this.matchExistingProgram(child);
          if (existing == null) {
            var index = this.context.programs.push("") - 1;
            child.index = index;
            child.name = "program" + index;
            this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
            this.context.decorators[index] = compiler.decorators;
            this.context.environments[index] = child;
            this.useDepths = this.useDepths || compiler.useDepths;
            this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
            child.useDepths = this.useDepths;
            child.useBlockParams = this.useBlockParams;
          } else {
            child.index = existing.index;
            child.name = "program" + existing.index;
            this.useDepths = this.useDepths || existing.useDepths;
            this.useBlockParams = this.useBlockParams || existing.useBlockParams;
          }
        }
      },
      matchExistingProgram: function matchExistingProgram(child) {
        for (var i = 0, len = this.context.environments.length; i < len; i++) {
          var environment = this.context.environments[i];
          if (environment && environment.equals(child)) {
            return environment;
          }
        }
      },
      programExpression: function programExpression(guid3) {
        var child = this.environment.children[guid3], programParams = [child.index, "data", child.blockParams];
        if (this.useBlockParams || this.useDepths) {
          programParams.push("blockParams");
        }
        if (this.useDepths) {
          programParams.push("depths");
        }
        return "container.program(" + programParams.join(", ") + ")";
      },
      useRegister: function useRegister(name) {
        if (!this.registers[name]) {
          this.registers[name] = true;
          this.registers.list.push(name);
        }
      },
      push: function push(expr) {
        if (!(expr instanceof Literal)) {
          expr = this.source.wrap(expr);
        }
        this.inlineStack.push(expr);
        return expr;
      },
      pushStackLiteral: function pushStackLiteral(item) {
        this.push(new Literal(item));
      },
      pushSource: function pushSource(source) {
        if (this.pendingContent) {
          this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
          this.pendingContent = void 0;
        }
        if (source) {
          this.source.push(source);
        }
      },
      replaceStack: function replaceStack(callback) {
        var prefix = ["("], stack = void 0, createdStack = void 0, usedLiteral = void 0;
        if (!this.isInline()) {
          throw new _exception2["default"]("replaceStack on non-inline");
        }
        var top2 = this.popStack(true);
        if (top2 instanceof Literal) {
          stack = [top2.value];
          prefix = ["(", stack];
          usedLiteral = true;
        } else {
          createdStack = true;
          var _name = this.incrStack();
          prefix = ["((", this.push(_name), " = ", top2, ")"];
          stack = this.topStack();
        }
        var item = callback.call(this, stack);
        if (!usedLiteral) {
          this.popStack();
        }
        if (createdStack) {
          this.stackSlot--;
        }
        this.push(prefix.concat(item, ")"));
      },
      incrStack: function incrStack() {
        this.stackSlot++;
        if (this.stackSlot > this.stackVars.length) {
          this.stackVars.push("stack" + this.stackSlot);
        }
        return this.topStackName();
      },
      topStackName: function topStackName() {
        return "stack" + this.stackSlot;
      },
      flushInline: function flushInline() {
        var inlineStack = this.inlineStack;
        this.inlineStack = [];
        for (var i = 0, len = inlineStack.length; i < len; i++) {
          var entry = inlineStack[i];
          if (entry instanceof Literal) {
            this.compileStack.push(entry);
          } else {
            var stack = this.incrStack();
            this.pushSource([stack, " = ", entry, ";"]);
            this.compileStack.push(stack);
          }
        }
      },
      isInline: function isInline() {
        return this.inlineStack.length;
      },
      popStack: function popStack(wrapped) {
        var inline = this.isInline(), item = (inline ? this.inlineStack : this.compileStack).pop();
        if (!wrapped && item instanceof Literal) {
          return item.value;
        } else {
          if (!inline) {
            if (!this.stackSlot) {
              throw new _exception2["default"]("Invalid stack pop");
            }
            this.stackSlot--;
          }
          return item;
        }
      },
      topStack: function topStack() {
        var stack = this.isInline() ? this.inlineStack : this.compileStack, item = stack[stack.length - 1];
        if (item instanceof Literal) {
          return item.value;
        } else {
          return item;
        }
      },
      contextName: function contextName(context) {
        if (this.useDepths && context) {
          return "depths[" + context + "]";
        } else {
          return "depth" + context;
        }
      },
      quotedString: function quotedString(str) {
        return this.source.quotedString(str);
      },
      objectLiteral: function objectLiteral(obj) {
        return this.source.objectLiteral(obj);
      },
      aliasable: function aliasable(name) {
        var ret = this.aliases[name];
        if (ret) {
          ret.referenceCount++;
          return ret;
        }
        ret = this.aliases[name] = this.source.wrap(name);
        ret.aliasable = true;
        ret.referenceCount = 1;
        return ret;
      },
      setupHelper: function setupHelper(paramSize, name, blockHelper) {
        var params = [], paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
        var foundHelper = this.nameLookup("helpers", name, "helper"), callContext = this.aliasable(this.contextName(0) + " != null ? " + this.contextName(0) + " : (container.nullContext || {})");
        return {
          params,
          paramsInit,
          name: foundHelper,
          callParams: [callContext].concat(params)
        };
      },
      setupParams: function setupParams(helper, paramSize, params) {
        var options = {}, contexts = [], types = [], ids = [], objectArgs = !params, param = void 0;
        if (objectArgs) {
          params = [];
        }
        options.name = this.quotedString(helper);
        options.hash = this.popStack();
        if (this.trackIds) {
          options.hashIds = this.popStack();
        }
        if (this.stringParams) {
          options.hashTypes = this.popStack();
          options.hashContexts = this.popStack();
        }
        var inverse = this.popStack(), program = this.popStack();
        if (program || inverse) {
          options.fn = program || "container.noop";
          options.inverse = inverse || "container.noop";
        }
        var i = paramSize;
        while (i--) {
          param = this.popStack();
          params[i] = param;
          if (this.trackIds) {
            ids[i] = this.popStack();
          }
          if (this.stringParams) {
            types[i] = this.popStack();
            contexts[i] = this.popStack();
          }
        }
        if (objectArgs) {
          options.args = this.source.generateArray(params);
        }
        if (this.trackIds) {
          options.ids = this.source.generateArray(ids);
        }
        if (this.stringParams) {
          options.types = this.source.generateArray(types);
          options.contexts = this.source.generateArray(contexts);
        }
        if (this.options.data) {
          options.data = "data";
        }
        if (this.useBlockParams) {
          options.blockParams = "blockParams";
        }
        return options;
      },
      setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
        var options = this.setupParams(helper, paramSize, params);
        options.loc = JSON.stringify(this.source.currentLocation);
        options = this.objectLiteral(options);
        if (useRegister) {
          this.useRegister("options");
          params.push("options");
          return ["options=", options];
        } else if (params) {
          params.push(options);
          return "";
        } else {
          return options;
        }
      }
    };
    (function() {
      var reservedWords = "break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" ");
      var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
      for (var i = 0, l2 = reservedWords.length; i < l2; i++) {
        compilerWords[reservedWords[i]] = true;
      }
    })();
    JavaScriptCompiler.isValidJavaScriptVariableName = function(name) {
      return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
    };
    function strictLookup(requireTerminal, compiler, parts, startPartIndex, type) {
      var stack = compiler.popStack(), len = parts.length;
      if (requireTerminal) {
        len--;
      }
      for (var i = startPartIndex; i < len; i++) {
        stack = compiler.nameLookup(stack, parts[i], type);
      }
      if (requireTerminal) {
        return [compiler.aliasable("container.strict"), "(", stack, ", ", compiler.quotedString(parts[len]), ", ", JSON.stringify(compiler.source.currentLocation), " )"];
      } else {
        return stack;
      }
    }
    exports["default"] = JavaScriptCompiler;
    module.exports = exports["default"];
  }
});

// node_modules/handlebars/dist/cjs/handlebars.js
var require_handlebars = __commonJS({
  "node_modules/handlebars/dist/cjs/handlebars.js"(exports, module) {
    "use strict";
    exports.__esModule = true;
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _handlebarsRuntime = require_handlebars_runtime();
    var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
    var _handlebarsCompilerAst = require_ast();
    var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
    var _handlebarsCompilerBase = require_base2();
    var _handlebarsCompilerCompiler = require_compiler();
    var _handlebarsCompilerJavascriptCompiler = require_javascript_compiler();
    var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
    var _handlebarsCompilerVisitor = require_visitor();
    var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
    var _handlebarsNoConflict = require_no_conflict();
    var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
    var _create = _handlebarsRuntime2["default"].create;
    function create2() {
      var hb = _create();
      hb.compile = function(input, options) {
        return _handlebarsCompilerCompiler.compile(input, options, hb);
      };
      hb.precompile = function(input, options) {
        return _handlebarsCompilerCompiler.precompile(input, options, hb);
      };
      hb.AST = _handlebarsCompilerAst2["default"];
      hb.Compiler = _handlebarsCompilerCompiler.Compiler;
      hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2["default"];
      hb.Parser = _handlebarsCompilerBase.parser;
      hb.parse = _handlebarsCompilerBase.parse;
      hb.parseWithoutProcessing = _handlebarsCompilerBase.parseWithoutProcessing;
      return hb;
    }
    var inst = create2();
    inst.create = create2;
    _handlebarsNoConflict2["default"](inst);
    inst.Visitor = _handlebarsCompilerVisitor2["default"];
    inst["default"] = inst;
    exports["default"] = inst;
    module.exports = exports["default"];
  }
});

// node_modules/leaflet/dist/leaflet-src.js
var require_leaflet_src = __commonJS({
  "node_modules/leaflet/dist/leaflet-src.js"(exports, module) {
    (function(global2, factory) {
      typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.leaflet = {}));
    })(exports, (function(exports2) {
      "use strict";
      var version3 = "1.9.4";
      function extend3(dest) {
        var i, j, len, src;
        for (j = 1, len = arguments.length; j < len; j++) {
          src = arguments[j];
          for (i in src) {
            dest[i] = src[i];
          }
        }
        return dest;
      }
      var create$2 = Object.create || /* @__PURE__ */ (function() {
        function F() {
        }
        return function(proto) {
          F.prototype = proto;
          return new F();
        };
      })();
      function bind(fn, obj) {
        var slice2 = Array.prototype.slice;
        if (fn.bind) {
          return fn.bind.apply(fn, slice2.call(arguments, 1));
        }
        var args = slice2.call(arguments, 2);
        return function() {
          return fn.apply(obj, args.length ? args.concat(slice2.call(arguments)) : arguments);
        };
      }
      var lastId = 0;
      function stamp(obj) {
        if (!("_leaflet_id" in obj)) {
          obj["_leaflet_id"] = ++lastId;
        }
        return obj._leaflet_id;
      }
      function throttle(fn, time3, context) {
        var lock, args, wrapperFn, later;
        later = function() {
          lock = false;
          if (args) {
            wrapperFn.apply(context, args);
            args = false;
          }
        };
        wrapperFn = function() {
          if (lock) {
            args = arguments;
          } else {
            fn.apply(context, arguments);
            setTimeout(later, time3);
            lock = true;
          }
        };
        return wrapperFn;
      }
      function wrapNum(x2, range, includeMax) {
        var max = range[1], min = range[0], d = max - min;
        return x2 === max && includeMax ? x2 : ((x2 - min) % d + d) % d + min;
      }
      function falseFn() {
        return false;
      }
      function formatNum(num, precision) {
        if (precision === false) {
          return num;
        }
        var pow = Math.pow(10, precision === void 0 ? 6 : precision);
        return Math.round(num * pow) / pow;
      }
      function trim2(str) {
        return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, "");
      }
      function splitWords(str) {
        return trim2(str).split(/\s+/);
      }
      function setOptions(obj, options) {
        if (!Object.prototype.hasOwnProperty.call(obj, "options")) {
          obj.options = obj.options ? create$2(obj.options) : {};
        }
        for (var i in options) {
          obj.options[i] = options[i];
        }
        return obj.options;
      }
      function getParamString(obj, existingUrl, uppercase2) {
        var params = [];
        for (var i in obj) {
          params.push(encodeURIComponent(uppercase2 ? i.toUpperCase() : i) + "=" + encodeURIComponent(obj[i]));
        }
        return (!existingUrl || existingUrl.indexOf("?") === -1 ? "?" : "&") + params.join("&");
      }
      var templateRe = /\{ *([\w_ -]+) *\}/g;
      function template(str, data) {
        return str.replace(templateRe, function(str2, key) {
          var value = data[key];
          if (value === void 0) {
            throw new Error("No value provided for variable " + str2);
          } else if (typeof value === "function") {
            value = value(data);
          }
          return value;
        });
      }
      var isArray = Array.isArray || function(obj) {
        return Object.prototype.toString.call(obj) === "[object Array]";
      };
      function indexOf(array3, el) {
        for (var i = 0; i < array3.length; i++) {
          if (array3[i] === el) {
            return i;
          }
        }
        return -1;
      }
      var emptyImageUrl = "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";
      function getPrefixed(name) {
        return window["webkit" + name] || window["moz" + name] || window["ms" + name];
      }
      var lastTime = 0;
      function timeoutDefer(fn) {
        var time3 = +/* @__PURE__ */ new Date(), timeToCall = Math.max(0, 16 - (time3 - lastTime));
        lastTime = time3 + timeToCall;
        return window.setTimeout(fn, timeToCall);
      }
      var requestFn = window.requestAnimationFrame || getPrefixed("RequestAnimationFrame") || timeoutDefer;
      var cancelFn = window.cancelAnimationFrame || getPrefixed("CancelAnimationFrame") || getPrefixed("CancelRequestAnimationFrame") || function(id2) {
        window.clearTimeout(id2);
      };
      function requestAnimFrame(fn, context, immediate) {
        if (immediate && requestFn === timeoutDefer) {
          fn.call(context);
        } else {
          return requestFn.call(window, bind(fn, context));
        }
      }
      function cancelAnimFrame(id2) {
        if (id2) {
          cancelFn.call(window, id2);
        }
      }
      var Util = {
        __proto__: null,
        extend: extend3,
        create: create$2,
        bind,
        get lastId() {
          return lastId;
        },
        stamp,
        throttle,
        wrapNum,
        falseFn,
        formatNum,
        trim: trim2,
        splitWords,
        setOptions,
        getParamString,
        template,
        isArray,
        indexOf,
        emptyImageUrl,
        requestFn,
        cancelFn,
        requestAnimFrame,
        cancelAnimFrame
      };
      function Class2() {
      }
      Class2.extend = function(props) {
        var NewClass = function() {
          setOptions(this);
          if (this.initialize) {
            this.initialize.apply(this, arguments);
          }
          this.callInitHooks();
        };
        var parentProto = NewClass.__super__ = this.prototype;
        var proto = create$2(parentProto);
        proto.constructor = NewClass;
        NewClass.prototype = proto;
        for (var i in this) {
          if (Object.prototype.hasOwnProperty.call(this, i) && i !== "prototype" && i !== "__super__") {
            NewClass[i] = this[i];
          }
        }
        if (props.statics) {
          extend3(NewClass, props.statics);
        }
        if (props.includes) {
          checkDeprecatedMixinEvents(props.includes);
          extend3.apply(null, [proto].concat(props.includes));
        }
        extend3(proto, props);
        delete proto.statics;
        delete proto.includes;
        if (proto.options) {
          proto.options = parentProto.options ? create$2(parentProto.options) : {};
          extend3(proto.options, props.options);
        }
        proto._initHooks = [];
        proto.callInitHooks = function() {
          if (this._initHooksCalled) {
            return;
          }
          if (parentProto.callInitHooks) {
            parentProto.callInitHooks.call(this);
          }
          this._initHooksCalled = true;
          for (var i2 = 0, len = proto._initHooks.length; i2 < len; i2++) {
            proto._initHooks[i2].call(this);
          }
        };
        return NewClass;
      };
      Class2.include = function(props) {
        var parentOptions = this.prototype.options;
        extend3(this.prototype, props);
        if (props.options) {
          this.prototype.options = parentOptions;
          this.mergeOptions(props.options);
        }
        return this;
      };
      Class2.mergeOptions = function(options) {
        extend3(this.prototype.options, options);
        return this;
      };
      Class2.addInitHook = function(fn) {
        var args = Array.prototype.slice.call(arguments, 1);
        var init2 = typeof fn === "function" ? fn : function() {
          this[fn].apply(this, args);
        };
        this.prototype._initHooks = this.prototype._initHooks || [];
        this.prototype._initHooks.push(init2);
        return this;
      };
      function checkDeprecatedMixinEvents(includes) {
        if (typeof L === "undefined" || !L || !L.Mixin) {
          return;
        }
        includes = isArray(includes) ? includes : [includes];
        for (var i = 0; i < includes.length; i++) {
          if (includes[i] === L.Mixin.Events) {
            console.warn("Deprecated include of L.Mixin.Events: this property will be removed in future releases, please inherit from L.Evented instead.", new Error().stack);
          }
        }
      }
      var Events = {
        /* @method on(type: String, fn: Function, context?: Object): this
         * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).
         *
         * @alternative
         * @method on(eventMap: Object): this
         * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
         */
        on: function(types, fn, context) {
          if (typeof types === "object") {
            for (var type in types) {
              this._on(type, types[type], fn);
            }
          } else {
            types = splitWords(types);
            for (var i = 0, len = types.length; i < len; i++) {
              this._on(types[i], fn, context);
            }
          }
          return this;
        },
        /* @method off(type: String, fn?: Function, context?: Object): this
         * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.
         *
         * @alternative
         * @method off(eventMap: Object): this
         * Removes a set of type/listener pairs.
         *
         * @alternative
         * @method off: this
         * Removes all listeners to all events on the object. This includes implicitly attached events.
         */
        off: function(types, fn, context) {
          if (!arguments.length) {
            delete this._events;
          } else if (typeof types === "object") {
            for (var type in types) {
              this._off(type, types[type], fn);
            }
          } else {
            types = splitWords(types);
            var removeAll = arguments.length === 1;
            for (var i = 0, len = types.length; i < len; i++) {
              if (removeAll) {
                this._off(types[i]);
              } else {
                this._off(types[i], fn, context);
              }
            }
          }
          return this;
        },
        // attach listener (without syntactic sugar now)
        _on: function(type, fn, context, _once) {
          if (typeof fn !== "function") {
            console.warn("wrong listener type: " + typeof fn);
            return;
          }
          if (this._listens(type, fn, context) !== false) {
            return;
          }
          if (context === this) {
            context = void 0;
          }
          var newListener = { fn, ctx: context };
          if (_once) {
            newListener.once = true;
          }
          this._events = this._events || {};
          this._events[type] = this._events[type] || [];
          this._events[type].push(newListener);
        },
        _off: function(type, fn, context) {
          var listeners, i, len;
          if (!this._events) {
            return;
          }
          listeners = this._events[type];
          if (!listeners) {
            return;
          }
          if (arguments.length === 1) {
            if (this._firingCount) {
              for (i = 0, len = listeners.length; i < len; i++) {
                listeners[i].fn = falseFn;
              }
            }
            delete this._events[type];
            return;
          }
          if (typeof fn !== "function") {
            console.warn("wrong listener type: " + typeof fn);
            return;
          }
          var index2 = this._listens(type, fn, context);
          if (index2 !== false) {
            var listener = listeners[index2];
            if (this._firingCount) {
              listener.fn = falseFn;
              this._events[type] = listeners = listeners.slice();
            }
            listeners.splice(index2, 1);
          }
        },
        // @method fire(type: String, data?: Object, propagate?: Boolean): this
        // Fires an event of the specified type. You can optionally provide a data
        // object — the first argument of the listener function will contain its
        // properties. The event can optionally be propagated to event parents.
        fire: function(type, data, propagate) {
          if (!this.listens(type, propagate)) {
            return this;
          }
          var event = extend3({}, data, {
            type,
            target: this,
            sourceTarget: data && data.sourceTarget || this
          });
          if (this._events) {
            var listeners = this._events[type];
            if (listeners) {
              this._firingCount = this._firingCount + 1 || 1;
              for (var i = 0, len = listeners.length; i < len; i++) {
                var l2 = listeners[i];
                var fn = l2.fn;
                if (l2.once) {
                  this.off(type, fn, l2.ctx);
                }
                fn.call(l2.ctx || this, event);
              }
              this._firingCount--;
            }
          }
          if (propagate) {
            this._propagateEvent(event);
          }
          return this;
        },
        // @method listens(type: String, propagate?: Boolean): Boolean
        // @method listens(type: String, fn: Function, context?: Object, propagate?: Boolean): Boolean
        // Returns `true` if a particular event type has any listeners attached to it.
        // The verification can optionally be propagated, it will return `true` if parents have the listener attached to it.
        listens: function(type, fn, context, propagate) {
          if (typeof type !== "string") {
            console.warn('"string" type argument expected');
          }
          var _fn = fn;
          if (typeof fn !== "function") {
            propagate = !!fn;
            _fn = void 0;
            context = void 0;
          }
          var listeners = this._events && this._events[type];
          if (listeners && listeners.length) {
            if (this._listens(type, _fn, context) !== false) {
              return true;
            }
          }
          if (propagate) {
            for (var id2 in this._eventParents) {
              if (this._eventParents[id2].listens(type, fn, context, propagate)) {
                return true;
              }
            }
          }
          return false;
        },
        // returns the index (number) or false
        _listens: function(type, fn, context) {
          if (!this._events) {
            return false;
          }
          var listeners = this._events[type] || [];
          if (!fn) {
            return !!listeners.length;
          }
          if (context === this) {
            context = void 0;
          }
          for (var i = 0, len = listeners.length; i < len; i++) {
            if (listeners[i].fn === fn && listeners[i].ctx === context) {
              return i;
            }
          }
          return false;
        },
        // @method once(…): this
        // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
        once: function(types, fn, context) {
          if (typeof types === "object") {
            for (var type in types) {
              this._on(type, types[type], fn, true);
            }
          } else {
            types = splitWords(types);
            for (var i = 0, len = types.length; i < len; i++) {
              this._on(types[i], fn, context, true);
            }
          }
          return this;
        },
        // @method addEventParent(obj: Evented): this
        // Adds an event parent - an `Evented` that will receive propagated events
        addEventParent: function(obj) {
          this._eventParents = this._eventParents || {};
          this._eventParents[stamp(obj)] = obj;
          return this;
        },
        // @method removeEventParent(obj: Evented): this
        // Removes an event parent, so it will stop receiving propagated events
        removeEventParent: function(obj) {
          if (this._eventParents) {
            delete this._eventParents[stamp(obj)];
          }
          return this;
        },
        _propagateEvent: function(e) {
          for (var id2 in this._eventParents) {
            this._eventParents[id2].fire(e.type, extend3({
              layer: e.target,
              propagatedFrom: e.target
            }, e), true);
          }
        }
      };
      Events.addEventListener = Events.on;
      Events.removeEventListener = Events.clearAllEventListeners = Events.off;
      Events.addOneTimeEventListener = Events.once;
      Events.fireEvent = Events.fire;
      Events.hasEventListeners = Events.listens;
      var Evented = Class2.extend(Events);
      function Point(x2, y2, round) {
        this.x = round ? Math.round(x2) : x2;
        this.y = round ? Math.round(y2) : y2;
      }
      var trunc = Math.trunc || function(v) {
        return v > 0 ? Math.floor(v) : Math.ceil(v);
      };
      Point.prototype = {
        // @method clone(): Point
        // Returns a copy of the current point.
        clone: function() {
          return new Point(this.x, this.y);
        },
        // @method add(otherPoint: Point): Point
        // Returns the result of addition of the current and the given points.
        add: function(point) {
          return this.clone()._add(toPoint(point));
        },
        _add: function(point) {
          this.x += point.x;
          this.y += point.y;
          return this;
        },
        // @method subtract(otherPoint: Point): Point
        // Returns the result of subtraction of the given point from the current.
        subtract: function(point) {
          return this.clone()._subtract(toPoint(point));
        },
        _subtract: function(point) {
          this.x -= point.x;
          this.y -= point.y;
          return this;
        },
        // @method divideBy(num: Number): Point
        // Returns the result of division of the current point by the given number.
        divideBy: function(num) {
          return this.clone()._divideBy(num);
        },
        _divideBy: function(num) {
          this.x /= num;
          this.y /= num;
          return this;
        },
        // @method multiplyBy(num: Number): Point
        // Returns the result of multiplication of the current point by the given number.
        multiplyBy: function(num) {
          return this.clone()._multiplyBy(num);
        },
        _multiplyBy: function(num) {
          this.x *= num;
          this.y *= num;
          return this;
        },
        // @method scaleBy(scale: Point): Point
        // Multiply each coordinate of the current point by each coordinate of
        // `scale`. In linear algebra terms, multiply the point by the
        // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
        // defined by `scale`.
        scaleBy: function(point) {
          return new Point(this.x * point.x, this.y * point.y);
        },
        // @method unscaleBy(scale: Point): Point
        // Inverse of `scaleBy`. Divide each coordinate of the current point by
        // each coordinate of `scale`.
        unscaleBy: function(point) {
          return new Point(this.x / point.x, this.y / point.y);
        },
        // @method round(): Point
        // Returns a copy of the current point with rounded coordinates.
        round: function() {
          return this.clone()._round();
        },
        _round: function() {
          this.x = Math.round(this.x);
          this.y = Math.round(this.y);
          return this;
        },
        // @method floor(): Point
        // Returns a copy of the current point with floored coordinates (rounded down).
        floor: function() {
          return this.clone()._floor();
        },
        _floor: function() {
          this.x = Math.floor(this.x);
          this.y = Math.floor(this.y);
          return this;
        },
        // @method ceil(): Point
        // Returns a copy of the current point with ceiled coordinates (rounded up).
        ceil: function() {
          return this.clone()._ceil();
        },
        _ceil: function() {
          this.x = Math.ceil(this.x);
          this.y = Math.ceil(this.y);
          return this;
        },
        // @method trunc(): Point
        // Returns a copy of the current point with truncated coordinates (rounded towards zero).
        trunc: function() {
          return this.clone()._trunc();
        },
        _trunc: function() {
          this.x = trunc(this.x);
          this.y = trunc(this.y);
          return this;
        },
        // @method distanceTo(otherPoint: Point): Number
        // Returns the cartesian distance between the current and the given points.
        distanceTo: function(point) {
          point = toPoint(point);
          var x2 = point.x - this.x, y2 = point.y - this.y;
          return Math.sqrt(x2 * x2 + y2 * y2);
        },
        // @method equals(otherPoint: Point): Boolean
        // Returns `true` if the given point has the same coordinates.
        equals: function(point) {
          point = toPoint(point);
          return point.x === this.x && point.y === this.y;
        },
        // @method contains(otherPoint: Point): Boolean
        // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
        contains: function(point) {
          point = toPoint(point);
          return Math.abs(point.x) <= Math.abs(this.x) && Math.abs(point.y) <= Math.abs(this.y);
        },
        // @method toString(): String
        // Returns a string representation of the point for debugging purposes.
        toString: function() {
          return "Point(" + formatNum(this.x) + ", " + formatNum(this.y) + ")";
        }
      };
      function toPoint(x2, y2, round) {
        if (x2 instanceof Point) {
          return x2;
        }
        if (isArray(x2)) {
          return new Point(x2[0], x2[1]);
        }
        if (x2 === void 0 || x2 === null) {
          return x2;
        }
        if (typeof x2 === "object" && "x" in x2 && "y" in x2) {
          return new Point(x2.x, x2.y);
        }
        return new Point(x2, y2, round);
      }
      function Bounds(a, b) {
        if (!a) {
          return;
        }
        var points = b ? [a, b] : a;
        for (var i = 0, len = points.length; i < len; i++) {
          this.extend(points[i]);
        }
      }
      Bounds.prototype = {
        // @method extend(point: Point): this
        // Extends the bounds to contain the given point.
        // @alternative
        // @method extend(otherBounds: Bounds): this
        // Extend the bounds to contain the given bounds
        extend: function(obj) {
          var min2, max2;
          if (!obj) {
            return this;
          }
          if (obj instanceof Point || typeof obj[0] === "number" || "x" in obj) {
            min2 = max2 = toPoint(obj);
          } else {
            obj = toBounds(obj);
            min2 = obj.min;
            max2 = obj.max;
            if (!min2 || !max2) {
              return this;
            }
          }
          if (!this.min && !this.max) {
            this.min = min2.clone();
            this.max = max2.clone();
          } else {
            this.min.x = Math.min(min2.x, this.min.x);
            this.max.x = Math.max(max2.x, this.max.x);
            this.min.y = Math.min(min2.y, this.min.y);
            this.max.y = Math.max(max2.y, this.max.y);
          }
          return this;
        },
        // @method getCenter(round?: Boolean): Point
        // Returns the center point of the bounds.
        getCenter: function(round) {
          return toPoint(
            (this.min.x + this.max.x) / 2,
            (this.min.y + this.max.y) / 2,
            round
          );
        },
        // @method getBottomLeft(): Point
        // Returns the bottom-left point of the bounds.
        getBottomLeft: function() {
          return toPoint(this.min.x, this.max.y);
        },
        // @method getTopRight(): Point
        // Returns the top-right point of the bounds.
        getTopRight: function() {
          return toPoint(this.max.x, this.min.y);
        },
        // @method getTopLeft(): Point
        // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
        getTopLeft: function() {
          return this.min;
        },
        // @method getBottomRight(): Point
        // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
        getBottomRight: function() {
          return this.max;
        },
        // @method getSize(): Point
        // Returns the size of the given bounds
        getSize: function() {
          return this.max.subtract(this.min);
        },
        // @method contains(otherBounds: Bounds): Boolean
        // Returns `true` if the rectangle contains the given one.
        // @alternative
        // @method contains(point: Point): Boolean
        // Returns `true` if the rectangle contains the given point.
        contains: function(obj) {
          var min, max;
          if (typeof obj[0] === "number" || obj instanceof Point) {
            obj = toPoint(obj);
          } else {
            obj = toBounds(obj);
          }
          if (obj instanceof Bounds) {
            min = obj.min;
            max = obj.max;
          } else {
            min = max = obj;
          }
          return min.x >= this.min.x && max.x <= this.max.x && min.y >= this.min.y && max.y <= this.max.y;
        },
        // @method intersects(otherBounds: Bounds): Boolean
        // Returns `true` if the rectangle intersects the given bounds. Two bounds
        // intersect if they have at least one point in common.
        intersects: function(bounds) {
          bounds = toBounds(bounds);
          var min = this.min, max = this.max, min2 = bounds.min, max2 = bounds.max, xIntersects = max2.x >= min.x && min2.x <= max.x, yIntersects = max2.y >= min.y && min2.y <= max.y;
          return xIntersects && yIntersects;
        },
        // @method overlaps(otherBounds: Bounds): Boolean
        // Returns `true` if the rectangle overlaps the given bounds. Two bounds
        // overlap if their intersection is an area.
        overlaps: function(bounds) {
          bounds = toBounds(bounds);
          var min = this.min, max = this.max, min2 = bounds.min, max2 = bounds.max, xOverlaps = max2.x > min.x && min2.x < max.x, yOverlaps = max2.y > min.y && min2.y < max.y;
          return xOverlaps && yOverlaps;
        },
        // @method isValid(): Boolean
        // Returns `true` if the bounds are properly initialized.
        isValid: function() {
          return !!(this.min && this.max);
        },
        // @method pad(bufferRatio: Number): Bounds
        // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
        // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
        // Negative values will retract the bounds.
        pad: function(bufferRatio) {
          var min = this.min, max = this.max, heightBuffer = Math.abs(min.x - max.x) * bufferRatio, widthBuffer = Math.abs(min.y - max.y) * bufferRatio;
          return toBounds(
            toPoint(min.x - heightBuffer, min.y - widthBuffer),
            toPoint(max.x + heightBuffer, max.y + widthBuffer)
          );
        },
        // @method equals(otherBounds: Bounds): Boolean
        // Returns `true` if the rectangle is equivalent to the given bounds.
        equals: function(bounds) {
          if (!bounds) {
            return false;
          }
          bounds = toBounds(bounds);
          return this.min.equals(bounds.getTopLeft()) && this.max.equals(bounds.getBottomRight());
        }
      };
      function toBounds(a, b) {
        if (!a || a instanceof Bounds) {
          return a;
        }
        return new Bounds(a, b);
      }
      function LatLngBounds(corner1, corner2) {
        if (!corner1) {
          return;
        }
        var latlngs = corner2 ? [corner1, corner2] : corner1;
        for (var i = 0, len = latlngs.length; i < len; i++) {
          this.extend(latlngs[i]);
        }
      }
      LatLngBounds.prototype = {
        // @method extend(latlng: LatLng): this
        // Extend the bounds to contain the given point
        // @alternative
        // @method extend(otherBounds: LatLngBounds): this
        // Extend the bounds to contain the given bounds
        extend: function(obj) {
          var sw = this._southWest, ne = this._northEast, sw2, ne2;
          if (obj instanceof LatLng) {
            sw2 = obj;
            ne2 = obj;
          } else if (obj instanceof LatLngBounds) {
            sw2 = obj._southWest;
            ne2 = obj._northEast;
            if (!sw2 || !ne2) {
              return this;
            }
          } else {
            return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
          }
          if (!sw && !ne) {
            this._southWest = new LatLng(sw2.lat, sw2.lng);
            this._northEast = new LatLng(ne2.lat, ne2.lng);
          } else {
            sw.lat = Math.min(sw2.lat, sw.lat);
            sw.lng = Math.min(sw2.lng, sw.lng);
            ne.lat = Math.max(ne2.lat, ne.lat);
            ne.lng = Math.max(ne2.lng, ne.lng);
          }
          return this;
        },
        // @method pad(bufferRatio: Number): LatLngBounds
        // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
        // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
        // Negative values will retract the bounds.
        pad: function(bufferRatio) {
          var sw = this._southWest, ne = this._northEast, heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio, widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
          return new LatLngBounds(
            new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
            new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer)
          );
        },
        // @method getCenter(): LatLng
        // Returns the center point of the bounds.
        getCenter: function() {
          return new LatLng(
            (this._southWest.lat + this._northEast.lat) / 2,
            (this._southWest.lng + this._northEast.lng) / 2
          );
        },
        // @method getSouthWest(): LatLng
        // Returns the south-west point of the bounds.
        getSouthWest: function() {
          return this._southWest;
        },
        // @method getNorthEast(): LatLng
        // Returns the north-east point of the bounds.
        getNorthEast: function() {
          return this._northEast;
        },
        // @method getNorthWest(): LatLng
        // Returns the north-west point of the bounds.
        getNorthWest: function() {
          return new LatLng(this.getNorth(), this.getWest());
        },
        // @method getSouthEast(): LatLng
        // Returns the south-east point of the bounds.
        getSouthEast: function() {
          return new LatLng(this.getSouth(), this.getEast());
        },
        // @method getWest(): Number
        // Returns the west longitude of the bounds
        getWest: function() {
          return this._southWest.lng;
        },
        // @method getSouth(): Number
        // Returns the south latitude of the bounds
        getSouth: function() {
          return this._southWest.lat;
        },
        // @method getEast(): Number
        // Returns the east longitude of the bounds
        getEast: function() {
          return this._northEast.lng;
        },
        // @method getNorth(): Number
        // Returns the north latitude of the bounds
        getNorth: function() {
          return this._northEast.lat;
        },
        // @method contains(otherBounds: LatLngBounds): Boolean
        // Returns `true` if the rectangle contains the given one.
        // @alternative
        // @method contains (latlng: LatLng): Boolean
        // Returns `true` if the rectangle contains the given point.
        contains: function(obj) {
          if (typeof obj[0] === "number" || obj instanceof LatLng || "lat" in obj) {
            obj = toLatLng(obj);
          } else {
            obj = toLatLngBounds(obj);
          }
          var sw = this._southWest, ne = this._northEast, sw2, ne2;
          if (obj instanceof LatLngBounds) {
            sw2 = obj.getSouthWest();
            ne2 = obj.getNorthEast();
          } else {
            sw2 = ne2 = obj;
          }
          return sw2.lat >= sw.lat && ne2.lat <= ne.lat && sw2.lng >= sw.lng && ne2.lng <= ne.lng;
        },
        // @method intersects(otherBounds: LatLngBounds): Boolean
        // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
        intersects: function(bounds) {
          bounds = toLatLngBounds(bounds);
          var sw = this._southWest, ne = this._northEast, sw2 = bounds.getSouthWest(), ne2 = bounds.getNorthEast(), latIntersects = ne2.lat >= sw.lat && sw2.lat <= ne.lat, lngIntersects = ne2.lng >= sw.lng && sw2.lng <= ne.lng;
          return latIntersects && lngIntersects;
        },
        // @method overlaps(otherBounds: LatLngBounds): Boolean
        // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
        overlaps: function(bounds) {
          bounds = toLatLngBounds(bounds);
          var sw = this._southWest, ne = this._northEast, sw2 = bounds.getSouthWest(), ne2 = bounds.getNorthEast(), latOverlaps = ne2.lat > sw.lat && sw2.lat < ne.lat, lngOverlaps = ne2.lng > sw.lng && sw2.lng < ne.lng;
          return latOverlaps && lngOverlaps;
        },
        // @method toBBoxString(): String
        // Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.
        toBBoxString: function() {
          return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(",");
        },
        // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
        // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.
        equals: function(bounds, maxMargin) {
          if (!bounds) {
            return false;
          }
          bounds = toLatLngBounds(bounds);
          return this._southWest.equals(bounds.getSouthWest(), maxMargin) && this._northEast.equals(bounds.getNorthEast(), maxMargin);
        },
        // @method isValid(): Boolean
        // Returns `true` if the bounds are properly initialized.
        isValid: function() {
          return !!(this._southWest && this._northEast);
        }
      };
      function toLatLngBounds(a, b) {
        if (a instanceof LatLngBounds) {
          return a;
        }
        return new LatLngBounds(a, b);
      }
      function LatLng(lat, lng, alt) {
        if (isNaN(lat) || isNaN(lng)) {
          throw new Error("Invalid LatLng object: (" + lat + ", " + lng + ")");
        }
        this.lat = +lat;
        this.lng = +lng;
        if (alt !== void 0) {
          this.alt = +alt;
        }
      }
      LatLng.prototype = {
        // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
        // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.
        equals: function(obj, maxMargin) {
          if (!obj) {
            return false;
          }
          obj = toLatLng(obj);
          var margin = Math.max(
            Math.abs(this.lat - obj.lat),
            Math.abs(this.lng - obj.lng)
          );
          return margin <= (maxMargin === void 0 ? 1e-9 : maxMargin);
        },
        // @method toString(): String
        // Returns a string representation of the point (for debugging purposes).
        toString: function(precision) {
          return "LatLng(" + formatNum(this.lat, precision) + ", " + formatNum(this.lng, precision) + ")";
        },
        // @method distanceTo(otherLatLng: LatLng): Number
        // Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).
        distanceTo: function(other) {
          return Earth.distance(this, toLatLng(other));
        },
        // @method wrap(): LatLng
        // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
        wrap: function() {
          return Earth.wrapLatLng(this);
        },
        // @method toBounds(sizeInMeters: Number): LatLngBounds
        // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
        toBounds: function(sizeInMeters) {
          var latAccuracy = 180 * sizeInMeters / 40075017, lngAccuracy = latAccuracy / Math.cos(Math.PI / 180 * this.lat);
          return toLatLngBounds(
            [this.lat - latAccuracy, this.lng - lngAccuracy],
            [this.lat + latAccuracy, this.lng + lngAccuracy]
          );
        },
        clone: function() {
          return new LatLng(this.lat, this.lng, this.alt);
        }
      };
      function toLatLng(a, b, c) {
        if (a instanceof LatLng) {
          return a;
        }
        if (isArray(a) && typeof a[0] !== "object") {
          if (a.length === 3) {
            return new LatLng(a[0], a[1], a[2]);
          }
          if (a.length === 2) {
            return new LatLng(a[0], a[1]);
          }
          return null;
        }
        if (a === void 0 || a === null) {
          return a;
        }
        if (typeof a === "object" && "lat" in a) {
          return new LatLng(a.lat, "lng" in a ? a.lng : a.lon, a.alt);
        }
        if (b === void 0) {
          return null;
        }
        return new LatLng(a, b, c);
      }
      var CRS = {
        // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
        // Projects geographical coordinates into pixel coordinates for a given zoom.
        latLngToPoint: function(latlng, zoom2) {
          var projectedPoint = this.projection.project(latlng), scale2 = this.scale(zoom2);
          return this.transformation._transform(projectedPoint, scale2);
        },
        // @method pointToLatLng(point: Point, zoom: Number): LatLng
        // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
        // zoom into geographical coordinates.
        pointToLatLng: function(point, zoom2) {
          var scale2 = this.scale(zoom2), untransformedPoint = this.transformation.untransform(point, scale2);
          return this.projection.unproject(untransformedPoint);
        },
        // @method project(latlng: LatLng): Point
        // Projects geographical coordinates into coordinates in units accepted for
        // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
        project: function(latlng) {
          return this.projection.project(latlng);
        },
        // @method unproject(point: Point): LatLng
        // Given a projected coordinate returns the corresponding LatLng.
        // The inverse of `project`.
        unproject: function(point) {
          return this.projection.unproject(point);
        },
        // @method scale(zoom: Number): Number
        // Returns the scale used when transforming projected coordinates into
        // pixel coordinates for a particular zoom. For example, it returns
        // `256 * 2^zoom` for Mercator-based CRS.
        scale: function(zoom2) {
          return 256 * Math.pow(2, zoom2);
        },
        // @method zoom(scale: Number): Number
        // Inverse of `scale()`, returns the zoom level corresponding to a scale
        // factor of `scale`.
        zoom: function(scale2) {
          return Math.log(scale2 / 256) / Math.LN2;
        },
        // @method getProjectedBounds(zoom: Number): Bounds
        // Returns the projection's bounds scaled and transformed for the provided `zoom`.
        getProjectedBounds: function(zoom2) {
          if (this.infinite) {
            return null;
          }
          var b = this.projection.bounds, s2 = this.scale(zoom2), min = this.transformation.transform(b.min, s2), max = this.transformation.transform(b.max, s2);
          return new Bounds(min, max);
        },
        // @method distance(latlng1: LatLng, latlng2: LatLng): Number
        // Returns the distance between two geographical coordinates.
        // @property code: String
        // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
        //
        // @property wrapLng: Number[]
        // An array of two numbers defining whether the longitude (horizontal) coordinate
        // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
        // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
        //
        // @property wrapLat: Number[]
        // Like `wrapLng`, but for the latitude (vertical) axis.
        // wrapLng: [min, max],
        // wrapLat: [min, max],
        // @property infinite: Boolean
        // If true, the coordinate space will be unbounded (infinite in both axes)
        infinite: false,
        // @method wrapLatLng(latlng: LatLng): LatLng
        // Returns a `LatLng` where lat and lng has been wrapped according to the
        // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
        wrapLatLng: function(latlng) {
          var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng, lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat, alt = latlng.alt;
          return new LatLng(lat, lng, alt);
        },
        // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
        // Returns a `LatLngBounds` with the same size as the given one, ensuring
        // that its center is within the CRS's bounds.
        // Only accepts actual `L.LatLngBounds` instances, not arrays.
        wrapLatLngBounds: function(bounds) {
          var center2 = bounds.getCenter(), newCenter = this.wrapLatLng(center2), latShift = center2.lat - newCenter.lat, lngShift = center2.lng - newCenter.lng;
          if (latShift === 0 && lngShift === 0) {
            return bounds;
          }
          var sw = bounds.getSouthWest(), ne = bounds.getNorthEast(), newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift), newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
          return new LatLngBounds(newSw, newNe);
        }
      };
      var Earth = extend3({}, CRS, {
        wrapLng: [-180, 180],
        // Mean Earth Radius, as recommended for use by
        // the International Union of Geodesy and Geophysics,
        // see https://rosettacode.org/wiki/Haversine_formula
        R: 6371e3,
        // distance between two geographical points using spherical law of cosines approximation
        distance: function(latlng1, latlng2) {
          var rad = Math.PI / 180, lat1 = latlng1.lat * rad, lat2 = latlng2.lat * rad, sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2), sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2), a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon, c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
          return this.R * c;
        }
      });
      var earthRadius = 6378137;
      var SphericalMercator = {
        R: earthRadius,
        MAX_LATITUDE: 85.0511287798,
        project: function(latlng) {
          var d = Math.PI / 180, max = this.MAX_LATITUDE, lat = Math.max(Math.min(max, latlng.lat), -max), sin = Math.sin(lat * d);
          return new Point(
            this.R * latlng.lng * d,
            this.R * Math.log((1 + sin) / (1 - sin)) / 2
          );
        },
        unproject: function(point) {
          var d = 180 / Math.PI;
          return new LatLng(
            (2 * Math.atan(Math.exp(point.y / this.R)) - Math.PI / 2) * d,
            point.x * d / this.R
          );
        },
        bounds: (function() {
          var d = earthRadius * Math.PI;
          return new Bounds([-d, -d], [d, d]);
        })()
      };
      function Transformation(a, b, c, d) {
        if (isArray(a)) {
          this._a = a[0];
          this._b = a[1];
          this._c = a[2];
          this._d = a[3];
          return;
        }
        this._a = a;
        this._b = b;
        this._c = c;
        this._d = d;
      }
      Transformation.prototype = {
        // @method transform(point: Point, scale?: Number): Point
        // Returns a transformed point, optionally multiplied by the given scale.
        // Only accepts actual `L.Point` instances, not arrays.
        transform: function(point, scale2) {
          return this._transform(point.clone(), scale2);
        },
        // destructive transform (faster)
        _transform: function(point, scale2) {
          scale2 = scale2 || 1;
          point.x = scale2 * (this._a * point.x + this._b);
          point.y = scale2 * (this._c * point.y + this._d);
          return point;
        },
        // @method untransform(point: Point, scale?: Number): Point
        // Returns the reverse transformation of the given point, optionally divided
        // by the given scale. Only accepts actual `L.Point` instances, not arrays.
        untransform: function(point, scale2) {
          scale2 = scale2 || 1;
          return new Point(
            (point.x / scale2 - this._b) / this._a,
            (point.y / scale2 - this._d) / this._c
          );
        }
      };
      function toTransformation(a, b, c, d) {
        return new Transformation(a, b, c, d);
      }
      var EPSG3857 = extend3({}, Earth, {
        code: "EPSG:3857",
        projection: SphericalMercator,
        transformation: (function() {
          var scale2 = 0.5 / (Math.PI * SphericalMercator.R);
          return toTransformation(scale2, 0.5, -scale2, 0.5);
        })()
      });
      var EPSG900913 = extend3({}, EPSG3857, {
        code: "EPSG:900913"
      });
      function svgCreate(name) {
        return document.createElementNS("http://www.w3.org/2000/svg", name);
      }
      function pointsToPath(rings, closed) {
        var str = "", i, j, len, len2, points, p;
        for (i = 0, len = rings.length; i < len; i++) {
          points = rings[i];
          for (j = 0, len2 = points.length; j < len2; j++) {
            p = points[j];
            str += (j ? "L" : "M") + p.x + " " + p.y;
          }
          str += closed ? Browser.svg ? "z" : "x" : "";
        }
        return str || "M0 0";
      }
      var style = document.documentElement.style;
      var ie = "ActiveXObject" in window;
      var ielt9 = ie && !document.addEventListener;
      var edge = "msLaunchUri" in navigator && !("documentMode" in document);
      var webkit = userAgentContains("webkit");
      var android = userAgentContains("android");
      var android23 = userAgentContains("android 2") || userAgentContains("android 3");
      var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10);
      var androidStock = android && userAgentContains("Google") && webkitVer < 537 && !("AudioNode" in window);
      var opera = !!window.opera;
      var chrome = !edge && userAgentContains("chrome");
      var gecko = userAgentContains("gecko") && !webkit && !opera && !ie;
      var safari = !chrome && userAgentContains("safari");
      var phantom = userAgentContains("phantom");
      var opera12 = "OTransition" in style;
      var win = navigator.platform.indexOf("Win") === 0;
      var ie3d = ie && "transition" in style;
      var webkit3d = "WebKitCSSMatrix" in window && "m11" in new window.WebKitCSSMatrix() && !android23;
      var gecko3d = "MozPerspective" in style;
      var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
      var mobile = typeof orientation !== "undefined" || userAgentContains("mobile");
      var mobileWebkit = mobile && webkit;
      var mobileWebkit3d = mobile && webkit3d;
      var msPointer = !window.PointerEvent && window.MSPointerEvent;
      var pointer = !!(window.PointerEvent || msPointer);
      var touchNative = "ontouchstart" in window || !!window.TouchEvent;
      var touch = !window.L_NO_TOUCH && (touchNative || pointer);
      var mobileOpera = mobile && opera;
      var mobileGecko = mobile && gecko;
      var retina = (window.devicePixelRatio || window.screen.deviceXDPI / window.screen.logicalXDPI) > 1;
      var passiveEvents = (function() {
        var supportsPassiveOption = false;
        try {
          var opts = Object.defineProperty({}, "passive", {
            get: function() {
              supportsPassiveOption = true;
            }
          });
          window.addEventListener("testPassiveEventSupport", falseFn, opts);
          window.removeEventListener("testPassiveEventSupport", falseFn, opts);
        } catch (e) {
        }
        return supportsPassiveOption;
      })();
      var canvas$1 = (function() {
        return !!document.createElement("canvas").getContext;
      })();
      var svg$1 = !!(document.createElementNS && svgCreate("svg").createSVGRect);
      var inlineSvg = !!svg$1 && (function() {
        var div = document.createElement("div");
        div.innerHTML = "<svg/>";
        return (div.firstChild && div.firstChild.namespaceURI) === "http://www.w3.org/2000/svg";
      })();
      var vml = !svg$1 && (function() {
        try {
          var div = document.createElement("div");
          div.innerHTML = '<v:shape adj="1"/>';
          var shape = div.firstChild;
          shape.style.behavior = "url(#default#VML)";
          return shape && typeof shape.adj === "object";
        } catch (e) {
          return false;
        }
      })();
      var mac3 = navigator.platform.indexOf("Mac") === 0;
      var linux = navigator.platform.indexOf("Linux") === 0;
      function userAgentContains(str) {
        return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
      }
      var Browser = {
        ie,
        ielt9,
        edge,
        webkit,
        android,
        android23,
        androidStock,
        opera,
        chrome,
        gecko,
        safari,
        phantom,
        opera12,
        win,
        ie3d,
        webkit3d,
        gecko3d,
        any3d,
        mobile,
        mobileWebkit,
        mobileWebkit3d,
        msPointer,
        pointer,
        touch,
        touchNative,
        mobileOpera,
        mobileGecko,
        retina,
        passiveEvents,
        canvas: canvas$1,
        svg: svg$1,
        vml,
        inlineSvg,
        mac: mac3,
        linux
      };
      var POINTER_DOWN = Browser.msPointer ? "MSPointerDown" : "pointerdown";
      var POINTER_MOVE = Browser.msPointer ? "MSPointerMove" : "pointermove";
      var POINTER_UP = Browser.msPointer ? "MSPointerUp" : "pointerup";
      var POINTER_CANCEL = Browser.msPointer ? "MSPointerCancel" : "pointercancel";
      var pEvent = {
        touchstart: POINTER_DOWN,
        touchmove: POINTER_MOVE,
        touchend: POINTER_UP,
        touchcancel: POINTER_CANCEL
      };
      var handle = {
        touchstart: _onPointerStart,
        touchmove: _handlePointer,
        touchend: _handlePointer,
        touchcancel: _handlePointer
      };
      var _pointers = {};
      var _pointerDocListener = false;
      function addPointerListener(obj, type, handler) {
        if (type === "touchstart") {
          _addPointerDocListener();
        }
        if (!handle[type]) {
          console.warn("wrong event specified:", type);
          return falseFn;
        }
        handler = handle[type].bind(this, handler);
        obj.addEventListener(pEvent[type], handler, false);
        return handler;
      }
      function removePointerListener(obj, type, handler) {
        if (!pEvent[type]) {
          console.warn("wrong event specified:", type);
          return;
        }
        obj.removeEventListener(pEvent[type], handler, false);
      }
      function _globalPointerDown(e) {
        _pointers[e.pointerId] = e;
      }
      function _globalPointerMove(e) {
        if (_pointers[e.pointerId]) {
          _pointers[e.pointerId] = e;
        }
      }
      function _globalPointerUp(e) {
        delete _pointers[e.pointerId];
      }
      function _addPointerDocListener() {
        if (!_pointerDocListener) {
          document.addEventListener(POINTER_DOWN, _globalPointerDown, true);
          document.addEventListener(POINTER_MOVE, _globalPointerMove, true);
          document.addEventListener(POINTER_UP, _globalPointerUp, true);
          document.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
          _pointerDocListener = true;
        }
      }
      function _handlePointer(handler, e) {
        if (e.pointerType === (e.MSPOINTER_TYPE_MOUSE || "mouse")) {
          return;
        }
        e.touches = [];
        for (var i in _pointers) {
          e.touches.push(_pointers[i]);
        }
        e.changedTouches = [e];
        handler(e);
      }
      function _onPointerStart(handler, e) {
        if (e.MSPOINTER_TYPE_TOUCH && e.pointerType === e.MSPOINTER_TYPE_TOUCH) {
          preventDefault(e);
        }
        _handlePointer(handler, e);
      }
      function makeDblclick(event) {
        var newEvent = {}, prop, i;
        for (i in event) {
          prop = event[i];
          newEvent[i] = prop && prop.bind ? prop.bind(event) : prop;
        }
        event = newEvent;
        newEvent.type = "dblclick";
        newEvent.detail = 2;
        newEvent.isTrusted = false;
        newEvent._simulated = true;
        return newEvent;
      }
      var delay = 200;
      function addDoubleTapListener(obj, handler) {
        obj.addEventListener("dblclick", handler);
        var last = 0, detail;
        function simDblclick(e) {
          if (e.detail !== 1) {
            detail = e.detail;
            return;
          }
          if (e.pointerType === "mouse" || e.sourceCapabilities && !e.sourceCapabilities.firesTouchEvents) {
            return;
          }
          var path2 = getPropagationPath(e);
          if (path2.some(function(el) {
            return el instanceof HTMLLabelElement && el.attributes.for;
          }) && !path2.some(function(el) {
            return el instanceof HTMLInputElement || el instanceof HTMLSelectElement;
          })) {
            return;
          }
          var now3 = Date.now();
          if (now3 - last <= delay) {
            detail++;
            if (detail === 2) {
              handler(makeDblclick(e));
            }
          } else {
            detail = 1;
          }
          last = now3;
        }
        obj.addEventListener("click", simDblclick);
        return {
          dblclick: handler,
          simDblclick
        };
      }
      function removeDoubleTapListener(obj, handlers) {
        obj.removeEventListener("dblclick", handlers.dblclick);
        obj.removeEventListener("click", handlers.simDblclick);
      }
      var TRANSFORM = testProp(
        ["transform", "webkitTransform", "OTransform", "MozTransform", "msTransform"]
      );
      var TRANSITION = testProp(
        ["webkitTransition", "transition", "OTransition", "MozTransition", "msTransition"]
      );
      var TRANSITION_END = TRANSITION === "webkitTransition" || TRANSITION === "OTransition" ? TRANSITION + "End" : "transitionend";
      function get3(id2) {
        return typeof id2 === "string" ? document.getElementById(id2) : id2;
      }
      function getStyle(el, style2) {
        var value = el.style[style2] || el.currentStyle && el.currentStyle[style2];
        if ((!value || value === "auto") && document.defaultView) {
          var css = document.defaultView.getComputedStyle(el, null);
          value = css ? css[style2] : null;
        }
        return value === "auto" ? null : value;
      }
      function create$1(tagName, className, container) {
        var el = document.createElement(tagName);
        el.className = className || "";
        if (container) {
          container.appendChild(el);
        }
        return el;
      }
      function remove2(el) {
        var parent = el.parentNode;
        if (parent) {
          parent.removeChild(el);
        }
      }
      function empty2(el) {
        while (el.firstChild) {
          el.removeChild(el.firstChild);
        }
      }
      function toFront(el) {
        var parent = el.parentNode;
        if (parent && parent.lastChild !== el) {
          parent.appendChild(el);
        }
      }
      function toBack(el) {
        var parent = el.parentNode;
        if (parent && parent.firstChild !== el) {
          parent.insertBefore(el, parent.firstChild);
        }
      }
      function hasClass(el, name) {
        if (el.classList !== void 0) {
          return el.classList.contains(name);
        }
        var className = getClass(el);
        return className.length > 0 && new RegExp("(^|\\s)" + name + "(\\s|$)").test(className);
      }
      function addClass(el, name) {
        if (el.classList !== void 0) {
          var classes = splitWords(name);
          for (var i = 0, len = classes.length; i < len; i++) {
            el.classList.add(classes[i]);
          }
        } else if (!hasClass(el, name)) {
          var className = getClass(el);
          setClass(el, (className ? className + " " : "") + name);
        }
      }
      function removeClass(el, name) {
        if (el.classList !== void 0) {
          el.classList.remove(name);
        } else {
          setClass(el, trim2((" " + getClass(el) + " ").replace(" " + name + " ", " ")));
        }
      }
      function setClass(el, name) {
        if (el.className.baseVal === void 0) {
          el.className = name;
        } else {
          el.className.baseVal = name;
        }
      }
      function getClass(el) {
        if (el.correspondingElement) {
          el = el.correspondingElement;
        }
        return el.className.baseVal === void 0 ? el.className : el.className.baseVal;
      }
      function setOpacity(el, value) {
        if ("opacity" in el.style) {
          el.style.opacity = value;
        } else if ("filter" in el.style) {
          _setOpacityIE(el, value);
        }
      }
      function _setOpacityIE(el, value) {
        var filter2 = false, filterName = "DXImageTransform.Microsoft.Alpha";
        try {
          filter2 = el.filters.item(filterName);
        } catch (e) {
          if (value === 1) {
            return;
          }
        }
        value = Math.round(value * 100);
        if (filter2) {
          filter2.Enabled = value !== 100;
          filter2.Opacity = value;
        } else {
          el.style.filter += " progid:" + filterName + "(opacity=" + value + ")";
        }
      }
      function testProp(props) {
        var style2 = document.documentElement.style;
        for (var i = 0; i < props.length; i++) {
          if (props[i] in style2) {
            return props[i];
          }
        }
        return false;
      }
      function setTransform(el, offset2, scale2) {
        var pos = offset2 || new Point(0, 0);
        el.style[TRANSFORM] = (Browser.ie3d ? "translate(" + pos.x + "px," + pos.y + "px)" : "translate3d(" + pos.x + "px," + pos.y + "px,0)") + (scale2 ? " scale(" + scale2 + ")" : "");
      }
      function setPosition(el, point) {
        el._leaflet_pos = point;
        if (Browser.any3d) {
          setTransform(el, point);
        } else {
          el.style.left = point.x + "px";
          el.style.top = point.y + "px";
        }
      }
      function getPosition(el) {
        return el._leaflet_pos || new Point(0, 0);
      }
      var disableTextSelection;
      var enableTextSelection;
      var _userSelect;
      if ("onselectstart" in document) {
        disableTextSelection = function() {
          on(window, "selectstart", preventDefault);
        };
        enableTextSelection = function() {
          off(window, "selectstart", preventDefault);
        };
      } else {
        var userSelectProperty = testProp(
          ["userSelect", "WebkitUserSelect", "OUserSelect", "MozUserSelect", "msUserSelect"]
        );
        disableTextSelection = function() {
          if (userSelectProperty) {
            var style2 = document.documentElement.style;
            _userSelect = style2[userSelectProperty];
            style2[userSelectProperty] = "none";
          }
        };
        enableTextSelection = function() {
          if (userSelectProperty) {
            document.documentElement.style[userSelectProperty] = _userSelect;
            _userSelect = void 0;
          }
        };
      }
      function disableImageDrag() {
        on(window, "dragstart", preventDefault);
      }
      function enableImageDrag() {
        off(window, "dragstart", preventDefault);
      }
      var _outlineElement, _outlineStyle;
      function preventOutline(element) {
        while (element.tabIndex === -1) {
          element = element.parentNode;
        }
        if (!element.style) {
          return;
        }
        restoreOutline();
        _outlineElement = element;
        _outlineStyle = element.style.outlineStyle;
        element.style.outlineStyle = "none";
        on(window, "keydown", restoreOutline);
      }
      function restoreOutline() {
        if (!_outlineElement) {
          return;
        }
        _outlineElement.style.outlineStyle = _outlineStyle;
        _outlineElement = void 0;
        _outlineStyle = void 0;
        off(window, "keydown", restoreOutline);
      }
      function getSizedParentNode(element) {
        do {
          element = element.parentNode;
        } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);
        return element;
      }
      function getScale(element) {
        var rect = element.getBoundingClientRect();
        return {
          x: rect.width / element.offsetWidth || 1,
          y: rect.height / element.offsetHeight || 1,
          boundingClientRect: rect
        };
      }
      var DomUtil = {
        __proto__: null,
        TRANSFORM,
        TRANSITION,
        TRANSITION_END,
        get: get3,
        getStyle,
        create: create$1,
        remove: remove2,
        empty: empty2,
        toFront,
        toBack,
        hasClass,
        addClass,
        removeClass,
        setClass,
        getClass,
        setOpacity,
        testProp,
        setTransform,
        setPosition,
        getPosition,
        get disableTextSelection() {
          return disableTextSelection;
        },
        get enableTextSelection() {
          return enableTextSelection;
        },
        disableImageDrag,
        enableImageDrag,
        preventOutline,
        restoreOutline,
        getSizedParentNode,
        getScale
      };
      function on(obj, types, fn, context) {
        if (types && typeof types === "object") {
          for (var type in types) {
            addOne(obj, type, types[type], fn);
          }
        } else {
          types = splitWords(types);
          for (var i = 0, len = types.length; i < len; i++) {
            addOne(obj, types[i], fn, context);
          }
        }
        return this;
      }
      var eventsKey = "_leaflet_events";
      function off(obj, types, fn, context) {
        if (arguments.length === 1) {
          batchRemove(obj);
          delete obj[eventsKey];
        } else if (types && typeof types === "object") {
          for (var type in types) {
            removeOne(obj, type, types[type], fn);
          }
        } else {
          types = splitWords(types);
          if (arguments.length === 2) {
            batchRemove(obj, function(type2) {
              return indexOf(types, type2) !== -1;
            });
          } else {
            for (var i = 0, len = types.length; i < len; i++) {
              removeOne(obj, types[i], fn, context);
            }
          }
        }
        return this;
      }
      function batchRemove(obj, filterFn) {
        for (var id2 in obj[eventsKey]) {
          var type = id2.split(/\d/)[0];
          if (!filterFn || filterFn(type)) {
            removeOne(obj, type, null, null, id2);
          }
        }
      }
      var mouseSubst = {
        mouseenter: "mouseover",
        mouseleave: "mouseout",
        wheel: !("onwheel" in window) && "mousewheel"
      };
      function addOne(obj, type, fn, context) {
        var id2 = type + stamp(fn) + (context ? "_" + stamp(context) : "");
        if (obj[eventsKey] && obj[eventsKey][id2]) {
          return this;
        }
        var handler = function(e) {
          return fn.call(context || obj, e || window.event);
        };
        var originalHandler = handler;
        if (!Browser.touchNative && Browser.pointer && type.indexOf("touch") === 0) {
          handler = addPointerListener(obj, type, handler);
        } else if (Browser.touch && type === "dblclick") {
          handler = addDoubleTapListener(obj, handler);
        } else if ("addEventListener" in obj) {
          if (type === "touchstart" || type === "touchmove" || type === "wheel" || type === "mousewheel") {
            obj.addEventListener(mouseSubst[type] || type, handler, Browser.passiveEvents ? { passive: false } : false);
          } else if (type === "mouseenter" || type === "mouseleave") {
            handler = function(e) {
              e = e || window.event;
              if (isExternalTarget(obj, e)) {
                originalHandler(e);
              }
            };
            obj.addEventListener(mouseSubst[type], handler, false);
          } else {
            obj.addEventListener(type, originalHandler, false);
          }
        } else {
          obj.attachEvent("on" + type, handler);
        }
        obj[eventsKey] = obj[eventsKey] || {};
        obj[eventsKey][id2] = handler;
      }
      function removeOne(obj, type, fn, context, id2) {
        id2 = id2 || type + stamp(fn) + (context ? "_" + stamp(context) : "");
        var handler = obj[eventsKey] && obj[eventsKey][id2];
        if (!handler) {
          return this;
        }
        if (!Browser.touchNative && Browser.pointer && type.indexOf("touch") === 0) {
          removePointerListener(obj, type, handler);
        } else if (Browser.touch && type === "dblclick") {
          removeDoubleTapListener(obj, handler);
        } else if ("removeEventListener" in obj) {
          obj.removeEventListener(mouseSubst[type] || type, handler, false);
        } else {
          obj.detachEvent("on" + type, handler);
        }
        obj[eventsKey][id2] = null;
      }
      function stopPropagation(e) {
        if (e.stopPropagation) {
          e.stopPropagation();
        } else if (e.originalEvent) {
          e.originalEvent._stopped = true;
        } else {
          e.cancelBubble = true;
        }
        return this;
      }
      function disableScrollPropagation(el) {
        addOne(el, "wheel", stopPropagation);
        return this;
      }
      function disableClickPropagation(el) {
        on(el, "mousedown touchstart dblclick contextmenu", stopPropagation);
        el["_leaflet_disable_click"] = true;
        return this;
      }
      function preventDefault(e) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
        return this;
      }
      function stop(e) {
        preventDefault(e);
        stopPropagation(e);
        return this;
      }
      function getPropagationPath(ev) {
        if (ev.composedPath) {
          return ev.composedPath();
        }
        var path2 = [];
        var el = ev.target;
        while (el) {
          path2.push(el);
          el = el.parentNode;
        }
        return path2;
      }
      function getMousePosition(e, container) {
        if (!container) {
          return new Point(e.clientX, e.clientY);
        }
        var scale2 = getScale(container), offset2 = scale2.boundingClientRect;
        return new Point(
          // offset.left/top values are in page scale (like clientX/Y),
          // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
          (e.clientX - offset2.left) / scale2.x - container.clientLeft,
          (e.clientY - offset2.top) / scale2.y - container.clientTop
        );
      }
      var wheelPxFactor = Browser.linux && Browser.chrome ? window.devicePixelRatio : Browser.mac ? window.devicePixelRatio * 3 : window.devicePixelRatio > 0 ? 2 * window.devicePixelRatio : 1;
      function getWheelDelta(e) {
        return Browser.edge ? e.wheelDeltaY / 2 : (
          // Don't trust window-geometry-based delta
          e.deltaY && e.deltaMode === 0 ? -e.deltaY / wheelPxFactor : (
            // Pixels
            e.deltaY && e.deltaMode === 1 ? -e.deltaY * 20 : (
              // Lines
              e.deltaY && e.deltaMode === 2 ? -e.deltaY * 60 : (
                // Pages
                e.deltaX || e.deltaZ ? 0 : (
                  // Skip horizontal/depth wheel events
                  e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : (
                    // Legacy IE pixels
                    e.detail && Math.abs(e.detail) < 32765 ? -e.detail * 20 : (
                      // Legacy Moz lines
                      e.detail ? e.detail / -32765 * 60 : (
                        // Legacy Moz pages
                        0
                      )
                    )
                  )
                )
              )
            )
          )
        );
      }
      function isExternalTarget(el, e) {
        var related = e.relatedTarget;
        if (!related) {
          return true;
        }
        try {
          while (related && related !== el) {
            related = related.parentNode;
          }
        } catch (err) {
          return false;
        }
        return related !== el;
      }
      var DomEvent = {
        __proto__: null,
        on,
        off,
        stopPropagation,
        disableScrollPropagation,
        disableClickPropagation,
        preventDefault,
        stop,
        getPropagationPath,
        getMousePosition,
        getWheelDelta,
        isExternalTarget,
        addListener: on,
        removeListener: off
      };
      var PosAnimation = Evented.extend({
        // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
        // Run an animation of a given element to a new position, optionally setting
        // duration in seconds (`0.25` by default) and easing linearity factor (3rd
        // argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1),
        // `0.5` by default).
        run: function(el, newPos, duration3, easeLinearity) {
          this.stop();
          this._el = el;
          this._inProgress = true;
          this._duration = duration3 || 0.25;
          this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
          this._startPos = getPosition(el);
          this._offset = newPos.subtract(this._startPos);
          this._startTime = +/* @__PURE__ */ new Date();
          this.fire("start");
          this._animate();
        },
        // @method stop()
        // Stops the animation (if currently running).
        stop: function() {
          if (!this._inProgress) {
            return;
          }
          this._step(true);
          this._complete();
        },
        _animate: function() {
          this._animId = requestAnimFrame(this._animate, this);
          this._step();
        },
        _step: function(round) {
          var elapsed = +/* @__PURE__ */ new Date() - this._startTime, duration3 = this._duration * 1e3;
          if (elapsed < duration3) {
            this._runFrame(this._easeOut(elapsed / duration3), round);
          } else {
            this._runFrame(1);
            this._complete();
          }
        },
        _runFrame: function(progress, round) {
          var pos = this._startPos.add(this._offset.multiplyBy(progress));
          if (round) {
            pos._round();
          }
          setPosition(this._el, pos);
          this.fire("step");
        },
        _complete: function() {
          cancelAnimFrame(this._animId);
          this._inProgress = false;
          this.fire("end");
        },
        _easeOut: function(t) {
          return 1 - Math.pow(1 - t, this._easeOutPower);
        }
      });
      var Map2 = Evented.extend({
        options: {
          // @section Map State Options
          // @option crs: CRS = L.CRS.EPSG3857
          // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
          // sure what it means.
          crs: EPSG3857,
          // @option center: LatLng = undefined
          // Initial geographic center of the map
          center: void 0,
          // @option zoom: Number = undefined
          // Initial map zoom level
          zoom: void 0,
          // @option minZoom: Number = *
          // Minimum zoom level of the map.
          // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
          // the lowest of their `minZoom` options will be used instead.
          minZoom: void 0,
          // @option maxZoom: Number = *
          // Maximum zoom level of the map.
          // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
          // the highest of their `maxZoom` options will be used instead.
          maxZoom: void 0,
          // @option layers: Layer[] = []
          // Array of layers that will be added to the map initially
          layers: [],
          // @option maxBounds: LatLngBounds = null
          // When this option is set, the map restricts the view to the given
          // geographical bounds, bouncing the user back if the user tries to pan
          // outside the view. To set the restriction dynamically, use
          // [`setMaxBounds`](#map-setmaxbounds) method.
          maxBounds: void 0,
          // @option renderer: Renderer = *
          // The default method for drawing vector layers on the map. `L.SVG`
          // or `L.Canvas` by default depending on browser support.
          renderer: void 0,
          // @section Animation Options
          // @option zoomAnimation: Boolean = true
          // Whether the map zoom animation is enabled. By default it's enabled
          // in all browsers that support CSS3 Transitions except Android.
          zoomAnimation: true,
          // @option zoomAnimationThreshold: Number = 4
          // Won't animate zoom if the zoom difference exceeds this value.
          zoomAnimationThreshold: 4,
          // @option fadeAnimation: Boolean = true
          // Whether the tile fade animation is enabled. By default it's enabled
          // in all browsers that support CSS3 Transitions except Android.
          fadeAnimation: true,
          // @option markerZoomAnimation: Boolean = true
          // Whether markers animate their zoom with the zoom animation, if disabled
          // they will disappear for the length of the animation. By default it's
          // enabled in all browsers that support CSS3 Transitions except Android.
          markerZoomAnimation: true,
          // @option transform3DLimit: Number = 2^23
          // Defines the maximum size of a CSS translation transform. The default
          // value should not be changed unless a web browser positions layers in
          // the wrong place after doing a large `panBy`.
          transform3DLimit: 8388608,
          // Precision limit of a 32-bit float
          // @section Interaction Options
          // @option zoomSnap: Number = 1
          // Forces the map's zoom level to always be a multiple of this, particularly
          // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
          // By default, the zoom level snaps to the nearest integer; lower values
          // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
          // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
          zoomSnap: 1,
          // @option zoomDelta: Number = 1
          // Controls how much the map's zoom level will change after a
          // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
          // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
          // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
          zoomDelta: 1,
          // @option trackResize: Boolean = true
          // Whether the map automatically handles browser window resize to update itself.
          trackResize: true
        },
        initialize: function(id2, options) {
          options = setOptions(this, options);
          this._handlers = [];
          this._layers = {};
          this._zoomBoundLayers = {};
          this._sizeChanged = true;
          this._initContainer(id2);
          this._initLayout();
          this._onResize = bind(this._onResize, this);
          this._initEvents();
          if (options.maxBounds) {
            this.setMaxBounds(options.maxBounds);
          }
          if (options.zoom !== void 0) {
            this._zoom = this._limitZoom(options.zoom);
          }
          if (options.center && options.zoom !== void 0) {
            this.setView(toLatLng(options.center), options.zoom, { reset: true });
          }
          this.callInitHooks();
          this._zoomAnimated = TRANSITION && Browser.any3d && !Browser.mobileOpera && this.options.zoomAnimation;
          if (this._zoomAnimated) {
            this._createAnimProxy();
            on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
          }
          this._addLayers(this.options.layers);
        },
        // @section Methods for modifying map state
        // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
        // Sets the view of the map (geographical center and zoom) with the given
        // animation options.
        setView: function(center2, zoom2, options) {
          zoom2 = zoom2 === void 0 ? this._zoom : this._limitZoom(zoom2);
          center2 = this._limitCenter(toLatLng(center2), zoom2, this.options.maxBounds);
          options = options || {};
          this._stop();
          if (this._loaded && !options.reset && options !== true) {
            if (options.animate !== void 0) {
              options.zoom = extend3({ animate: options.animate }, options.zoom);
              options.pan = extend3({ animate: options.animate, duration: options.duration }, options.pan);
            }
            var moved = this._zoom !== zoom2 ? this._tryAnimatedZoom && this._tryAnimatedZoom(center2, zoom2, options.zoom) : this._tryAnimatedPan(center2, options.pan);
            if (moved) {
              clearTimeout(this._sizeTimer);
              return this;
            }
          }
          this._resetView(center2, zoom2, options.pan && options.pan.noMoveStart);
          return this;
        },
        // @method setZoom(zoom: Number, options?: Zoom/pan options): this
        // Sets the zoom of the map.
        setZoom: function(zoom2, options) {
          if (!this._loaded) {
            this._zoom = zoom2;
            return this;
          }
          return this.setView(this.getCenter(), zoom2, { zoom: options });
        },
        // @method zoomIn(delta?: Number, options?: Zoom options): this
        // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
        zoomIn: function(delta, options) {
          delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
          return this.setZoom(this._zoom + delta, options);
        },
        // @method zoomOut(delta?: Number, options?: Zoom options): this
        // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
        zoomOut: function(delta, options) {
          delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
          return this.setZoom(this._zoom - delta, options);
        },
        // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
        // Zooms the map while keeping a specified geographical point on the map
        // stationary (e.g. used internally for scroll zoom and double-click zoom).
        // @alternative
        // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
        // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
        setZoomAround: function(latlng, zoom2, options) {
          var scale2 = this.getZoomScale(zoom2), viewHalf = this.getSize().divideBy(2), containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng), centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale2), newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
          return this.setView(newCenter, zoom2, { zoom: options });
        },
        _getBoundsCenterZoom: function(bounds, options) {
          options = options || {};
          bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
          var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]), paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]), zoom2 = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
          zoom2 = typeof options.maxZoom === "number" ? Math.min(options.maxZoom, zoom2) : zoom2;
          if (zoom2 === Infinity) {
            return {
              center: bounds.getCenter(),
              zoom: zoom2
            };
          }
          var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2), swPoint = this.project(bounds.getSouthWest(), zoom2), nePoint = this.project(bounds.getNorthEast(), zoom2), center2 = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom2);
          return {
            center: center2,
            zoom: zoom2
          };
        },
        // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
        // Sets a map view that contains the given geographical bounds with the
        // maximum zoom level possible.
        fitBounds: function(bounds, options) {
          bounds = toLatLngBounds(bounds);
          if (!bounds.isValid()) {
            throw new Error("Bounds are not valid.");
          }
          var target = this._getBoundsCenterZoom(bounds, options);
          return this.setView(target.center, target.zoom, options);
        },
        // @method fitWorld(options?: fitBounds options): this
        // Sets a map view that mostly contains the whole world with the maximum
        // zoom level possible.
        fitWorld: function(options) {
          return this.fitBounds([[-90, -180], [90, 180]], options);
        },
        // @method panTo(latlng: LatLng, options?: Pan options): this
        // Pans the map to a given center.
        panTo: function(center2, options) {
          return this.setView(center2, this._zoom, { pan: options });
        },
        // @method panBy(offset: Point, options?: Pan options): this
        // Pans the map by a given number of pixels (animated).
        panBy: function(offset2, options) {
          offset2 = toPoint(offset2).round();
          options = options || {};
          if (!offset2.x && !offset2.y) {
            return this.fire("moveend");
          }
          if (options.animate !== true && !this.getSize().contains(offset2)) {
            this._resetView(this.unproject(this.project(this.getCenter()).add(offset2)), this.getZoom());
            return this;
          }
          if (!this._panAnim) {
            this._panAnim = new PosAnimation();
            this._panAnim.on({
              "step": this._onPanTransitionStep,
              "end": this._onPanTransitionEnd
            }, this);
          }
          if (!options.noMoveStart) {
            this.fire("movestart");
          }
          if (options.animate !== false) {
            addClass(this._mapPane, "leaflet-pan-anim");
            var newPos = this._getMapPanePos().subtract(offset2).round();
            this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
          } else {
            this._rawPanBy(offset2);
            this.fire("move").fire("moveend");
          }
          return this;
        },
        // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
        // Sets the view of the map (geographical center and zoom) performing a smooth
        // pan-zoom animation.
        flyTo: function(targetCenter, targetZoom, options) {
          options = options || {};
          if (options.animate === false || !Browser.any3d) {
            return this.setView(targetCenter, targetZoom, options);
          }
          this._stop();
          var from = this.project(this.getCenter()), to = this.project(targetCenter), size = this.getSize(), startZoom = this._zoom;
          targetCenter = toLatLng(targetCenter);
          targetZoom = targetZoom === void 0 ? startZoom : targetZoom;
          var w0 = Math.max(size.x, size.y), w1 = w0 * this.getZoomScale(startZoom, targetZoom), u1 = to.distanceTo(from) || 1, rho = 1.42, rho2 = rho * rho;
          function r(i) {
            var s1 = i ? -1 : 1, s2 = i ? w1 : w0, t12 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1, b1 = 2 * s2 * rho2 * u1, b = t12 / b1, sq = Math.sqrt(b * b + 1) - b;
            var log3 = sq < 1e-9 ? -18 : Math.log(sq);
            return log3;
          }
          function sinh(n2) {
            return (Math.exp(n2) - Math.exp(-n2)) / 2;
          }
          function cosh(n2) {
            return (Math.exp(n2) + Math.exp(-n2)) / 2;
          }
          function tanh(n2) {
            return sinh(n2) / cosh(n2);
          }
          var r0 = r(0);
          function w(s2) {
            return w0 * (cosh(r0) / cosh(r0 + rho * s2));
          }
          function u(s2) {
            return w0 * (cosh(r0) * tanh(r0 + rho * s2) - sinh(r0)) / rho2;
          }
          function easeOut(t) {
            return 1 - Math.pow(1 - t, 1.5);
          }
          var start2 = Date.now(), S = (r(1) - r0) / rho, duration3 = options.duration ? 1e3 * options.duration : 1e3 * S * 0.8;
          function frame2() {
            var t = (Date.now() - start2) / duration3, s2 = easeOut(t) * S;
            if (t <= 1) {
              this._flyToFrame = requestAnimFrame(frame2, this);
              this._move(
                this.unproject(from.add(to.subtract(from).multiplyBy(u(s2) / u1)), startZoom),
                this.getScaleZoom(w0 / w(s2), startZoom),
                { flyTo: true }
              );
            } else {
              this._move(targetCenter, targetZoom)._moveEnd(true);
            }
          }
          this._moveStart(true, options.noMoveStart);
          frame2.call(this);
          return this;
        },
        // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
        // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
        // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
        flyToBounds: function(bounds, options) {
          var target = this._getBoundsCenterZoom(bounds, options);
          return this.flyTo(target.center, target.zoom, options);
        },
        // @method setMaxBounds(bounds: LatLngBounds): this
        // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
        setMaxBounds: function(bounds) {
          bounds = toLatLngBounds(bounds);
          if (this.listens("moveend", this._panInsideMaxBounds)) {
            this.off("moveend", this._panInsideMaxBounds);
          }
          if (!bounds.isValid()) {
            this.options.maxBounds = null;
            return this;
          }
          this.options.maxBounds = bounds;
          if (this._loaded) {
            this._panInsideMaxBounds();
          }
          return this.on("moveend", this._panInsideMaxBounds);
        },
        // @method setMinZoom(zoom: Number): this
        // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
        setMinZoom: function(zoom2) {
          var oldZoom = this.options.minZoom;
          this.options.minZoom = zoom2;
          if (this._loaded && oldZoom !== zoom2) {
            this.fire("zoomlevelschange");
            if (this.getZoom() < this.options.minZoom) {
              return this.setZoom(zoom2);
            }
          }
          return this;
        },
        // @method setMaxZoom(zoom: Number): this
        // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
        setMaxZoom: function(zoom2) {
          var oldZoom = this.options.maxZoom;
          this.options.maxZoom = zoom2;
          if (this._loaded && oldZoom !== zoom2) {
            this.fire("zoomlevelschange");
            if (this.getZoom() > this.options.maxZoom) {
              return this.setZoom(zoom2);
            }
          }
          return this;
        },
        // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
        // Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.
        panInsideBounds: function(bounds, options) {
          this._enforcingBounds = true;
          var center2 = this.getCenter(), newCenter = this._limitCenter(center2, this._zoom, toLatLngBounds(bounds));
          if (!center2.equals(newCenter)) {
            this.panTo(newCenter, options);
          }
          this._enforcingBounds = false;
          return this;
        },
        // @method panInside(latlng: LatLng, options?: padding options): this
        // Pans the map the minimum amount to make the `latlng` visible. Use
        // padding options to fit the display to more restricted bounds.
        // If `latlng` is already within the (optionally padded) display bounds,
        // the map will not be panned.
        panInside: function(latlng, options) {
          options = options || {};
          var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]), paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]), pixelCenter = this.project(this.getCenter()), pixelPoint = this.project(latlng), pixelBounds = this.getPixelBounds(), paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]), paddedSize = paddedBounds.getSize();
          if (!paddedBounds.contains(pixelPoint)) {
            this._enforcingBounds = true;
            var centerOffset = pixelPoint.subtract(paddedBounds.getCenter());
            var offset2 = paddedBounds.extend(pixelPoint).getSize().subtract(paddedSize);
            pixelCenter.x += centerOffset.x < 0 ? -offset2.x : offset2.x;
            pixelCenter.y += centerOffset.y < 0 ? -offset2.y : offset2.y;
            this.panTo(this.unproject(pixelCenter), options);
            this._enforcingBounds = false;
          }
          return this;
        },
        // @method invalidateSize(options: Zoom/pan options): this
        // Checks if the map container size changed and updates the map if so —
        // call it after you've changed the map size dynamically, also animating
        // pan by default. If `options.pan` is `false`, panning will not occur.
        // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
        // that it doesn't happen often even if the method is called many
        // times in a row.
        // @alternative
        // @method invalidateSize(animate: Boolean): this
        // Checks if the map container size changed and updates the map if so —
        // call it after you've changed the map size dynamically, also animating
        // pan by default.
        invalidateSize: function(options) {
          if (!this._loaded) {
            return this;
          }
          options = extend3({
            animate: false,
            pan: true
          }, options === true ? { animate: true } : options);
          var oldSize = this.getSize();
          this._sizeChanged = true;
          this._lastCenter = null;
          var newSize = this.getSize(), oldCenter = oldSize.divideBy(2).round(), newCenter = newSize.divideBy(2).round(), offset2 = oldCenter.subtract(newCenter);
          if (!offset2.x && !offset2.y) {
            return this;
          }
          if (options.animate && options.pan) {
            this.panBy(offset2);
          } else {
            if (options.pan) {
              this._rawPanBy(offset2);
            }
            this.fire("move");
            if (options.debounceMoveend) {
              clearTimeout(this._sizeTimer);
              this._sizeTimer = setTimeout(bind(this.fire, this, "moveend"), 200);
            } else {
              this.fire("moveend");
            }
          }
          return this.fire("resize", {
            oldSize,
            newSize
          });
        },
        // @section Methods for modifying map state
        // @method stop(): this
        // Stops the currently running `panTo` or `flyTo` animation, if any.
        stop: function() {
          this.setZoom(this._limitZoom(this._zoom));
          if (!this.options.zoomSnap) {
            this.fire("viewreset");
          }
          return this._stop();
        },
        // @section Geolocation methods
        // @method locate(options?: Locate options): this
        // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
        // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
        // and optionally sets the map view to the user's location with respect to
        // detection accuracy (or to the world view if geolocation failed).
        // Note that, if your page doesn't use HTTPS, this method will fail in
        // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
        // See `Locate options` for more details.
        locate: function(options) {
          options = this._locateOptions = extend3({
            timeout: 1e4,
            watch: false
            // setView: false
            // maxZoom: <Number>
            // maximumAge: 0
            // enableHighAccuracy: false
          }, options);
          if (!("geolocation" in navigator)) {
            this._handleGeolocationError({
              code: 0,
              message: "Geolocation not supported."
            });
            return this;
          }
          var onResponse = bind(this._handleGeolocationResponse, this), onError = bind(this._handleGeolocationError, this);
          if (options.watch) {
            this._locationWatchId = navigator.geolocation.watchPosition(onResponse, onError, options);
          } else {
            navigator.geolocation.getCurrentPosition(onResponse, onError, options);
          }
          return this;
        },
        // @method stopLocate(): this
        // Stops watching location previously initiated by `map.locate({watch: true})`
        // and aborts resetting the map view if map.locate was called with
        // `{setView: true}`.
        stopLocate: function() {
          if (navigator.geolocation && navigator.geolocation.clearWatch) {
            navigator.geolocation.clearWatch(this._locationWatchId);
          }
          if (this._locateOptions) {
            this._locateOptions.setView = false;
          }
          return this;
        },
        _handleGeolocationError: function(error51) {
          if (!this._container._leaflet_id) {
            return;
          }
          var c = error51.code, message = error51.message || (c === 1 ? "permission denied" : c === 2 ? "position unavailable" : "timeout");
          if (this._locateOptions.setView && !this._loaded) {
            this.fitWorld();
          }
          this.fire("locationerror", {
            code: c,
            message: "Geolocation error: " + message + "."
          });
        },
        _handleGeolocationResponse: function(pos) {
          if (!this._container._leaflet_id) {
            return;
          }
          var lat = pos.coords.latitude, lng = pos.coords.longitude, latlng = new LatLng(lat, lng), bounds = latlng.toBounds(pos.coords.accuracy * 2), options = this._locateOptions;
          if (options.setView) {
            var zoom2 = this.getBoundsZoom(bounds);
            this.setView(latlng, options.maxZoom ? Math.min(zoom2, options.maxZoom) : zoom2);
          }
          var data = {
            latlng,
            bounds,
            timestamp: pos.timestamp
          };
          for (var i in pos.coords) {
            if (typeof pos.coords[i] === "number") {
              data[i] = pos.coords[i];
            }
          }
          this.fire("locationfound", data);
        },
        // TODO Appropriate docs section?
        // @section Other Methods
        // @method addHandler(name: String, HandlerClass: Function): this
        // Adds a new `Handler` to the map, given its name and constructor function.
        addHandler: function(name, HandlerClass) {
          if (!HandlerClass) {
            return this;
          }
          var handler = this[name] = new HandlerClass(this);
          this._handlers.push(handler);
          if (this.options[name]) {
            handler.enable();
          }
          return this;
        },
        // @method remove(): this
        // Destroys the map and clears all related event listeners.
        remove: function() {
          this._initEvents(true);
          if (this.options.maxBounds) {
            this.off("moveend", this._panInsideMaxBounds);
          }
          if (this._containerId !== this._container._leaflet_id) {
            throw new Error("Map container is being reused by another instance");
          }
          try {
            delete this._container._leaflet_id;
            delete this._containerId;
          } catch (e) {
            this._container._leaflet_id = void 0;
            this._containerId = void 0;
          }
          if (this._locationWatchId !== void 0) {
            this.stopLocate();
          }
          this._stop();
          remove2(this._mapPane);
          if (this._clearControlPos) {
            this._clearControlPos();
          }
          if (this._resizeRequest) {
            cancelAnimFrame(this._resizeRequest);
            this._resizeRequest = null;
          }
          this._clearHandlers();
          if (this._loaded) {
            this.fire("unload");
          }
          var i;
          for (i in this._layers) {
            this._layers[i].remove();
          }
          for (i in this._panes) {
            remove2(this._panes[i]);
          }
          this._layers = [];
          this._panes = [];
          delete this._mapPane;
          delete this._renderer;
          return this;
        },
        // @section Other Methods
        // @method createPane(name: String, container?: HTMLElement): HTMLElement
        // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
        // then returns it. The pane is created as a child of `container`, or
        // as a child of the main map pane if not set.
        createPane: function(name, container) {
          var className = "leaflet-pane" + (name ? " leaflet-" + name.replace("Pane", "") + "-pane" : ""), pane = create$1("div", className, container || this._mapPane);
          if (name) {
            this._panes[name] = pane;
          }
          return pane;
        },
        // @section Methods for Getting Map State
        // @method getCenter(): LatLng
        // Returns the geographical center of the map view
        getCenter: function() {
          this._checkIfLoaded();
          if (this._lastCenter && !this._moved()) {
            return this._lastCenter.clone();
          }
          return this.layerPointToLatLng(this._getCenterLayerPoint());
        },
        // @method getZoom(): Number
        // Returns the current zoom level of the map view
        getZoom: function() {
          return this._zoom;
        },
        // @method getBounds(): LatLngBounds
        // Returns the geographical bounds visible in the current map view
        getBounds: function() {
          var bounds = this.getPixelBounds(), sw = this.unproject(bounds.getBottomLeft()), ne = this.unproject(bounds.getTopRight());
          return new LatLngBounds(sw, ne);
        },
        // @method getMinZoom(): Number
        // Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default.
        getMinZoom: function() {
          return this.options.minZoom === void 0 ? this._layersMinZoom || 0 : this.options.minZoom;
        },
        // @method getMaxZoom(): Number
        // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
        getMaxZoom: function() {
          return this.options.maxZoom === void 0 ? this._layersMaxZoom === void 0 ? Infinity : this._layersMaxZoom : this.options.maxZoom;
        },
        // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
        // Returns the maximum zoom level on which the given bounds fit to the map
        // view in its entirety. If `inside` (optional) is set to `true`, the method
        // instead returns the minimum zoom level on which the map view fits into
        // the given bounds in its entirety.
        getBoundsZoom: function(bounds, inside, padding) {
          bounds = toLatLngBounds(bounds);
          padding = toPoint(padding || [0, 0]);
          var zoom2 = this.getZoom() || 0, min = this.getMinZoom(), max = this.getMaxZoom(), nw = bounds.getNorthWest(), se = bounds.getSouthEast(), size = this.getSize().subtract(padding), boundsSize = toBounds(this.project(se, zoom2), this.project(nw, zoom2)).getSize(), snap = Browser.any3d ? this.options.zoomSnap : 1, scalex = size.x / boundsSize.x, scaley = size.y / boundsSize.y, scale2 = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
          zoom2 = this.getScaleZoom(scale2, zoom2);
          if (snap) {
            zoom2 = Math.round(zoom2 / (snap / 100)) * (snap / 100);
            zoom2 = inside ? Math.ceil(zoom2 / snap) * snap : Math.floor(zoom2 / snap) * snap;
          }
          return Math.max(min, Math.min(max, zoom2));
        },
        // @method getSize(): Point
        // Returns the current size of the map container (in pixels).
        getSize: function() {
          if (!this._size || this._sizeChanged) {
            this._size = new Point(
              this._container.clientWidth || 0,
              this._container.clientHeight || 0
            );
            this._sizeChanged = false;
          }
          return this._size.clone();
        },
        // @method getPixelBounds(): Bounds
        // Returns the bounds of the current map view in projected pixel
        // coordinates (sometimes useful in layer and overlay implementations).
        getPixelBounds: function(center2, zoom2) {
          var topLeftPoint = this._getTopLeftPoint(center2, zoom2);
          return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
        },
        // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
        // the map pane? "left point of the map layer" can be confusing, specially
        // since there can be negative offsets.
        // @method getPixelOrigin(): Point
        // Returns the projected pixel coordinates of the top left point of
        // the map layer (useful in custom layer and overlay implementations).
        getPixelOrigin: function() {
          this._checkIfLoaded();
          return this._pixelOrigin;
        },
        // @method getPixelWorldBounds(zoom?: Number): Bounds
        // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
        // If `zoom` is omitted, the map's current zoom level is used.
        getPixelWorldBounds: function(zoom2) {
          return this.options.crs.getProjectedBounds(zoom2 === void 0 ? this.getZoom() : zoom2);
        },
        // @section Other Methods
        // @method getPane(pane: String|HTMLElement): HTMLElement
        // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
        getPane: function(pane) {
          return typeof pane === "string" ? this._panes[pane] : pane;
        },
        // @method getPanes(): Object
        // Returns a plain object containing the names of all [panes](#map-pane) as keys and
        // the panes as values.
        getPanes: function() {
          return this._panes;
        },
        // @method getContainer: HTMLElement
        // Returns the HTML element that contains the map.
        getContainer: function() {
          return this._container;
        },
        // @section Conversion Methods
        // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
        // Returns the scale factor to be applied to a map transition from zoom level
        // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
        getZoomScale: function(toZoom, fromZoom) {
          var crs = this.options.crs;
          fromZoom = fromZoom === void 0 ? this._zoom : fromZoom;
          return crs.scale(toZoom) / crs.scale(fromZoom);
        },
        // @method getScaleZoom(scale: Number, fromZoom: Number): Number
        // Returns the zoom level that the map would end up at, if it is at `fromZoom`
        // level and everything is scaled by a factor of `scale`. Inverse of
        // [`getZoomScale`](#map-getZoomScale).
        getScaleZoom: function(scale2, fromZoom) {
          var crs = this.options.crs;
          fromZoom = fromZoom === void 0 ? this._zoom : fromZoom;
          var zoom2 = crs.zoom(scale2 * crs.scale(fromZoom));
          return isNaN(zoom2) ? Infinity : zoom2;
        },
        // @method project(latlng: LatLng, zoom: Number): Point
        // Projects a geographical coordinate `LatLng` according to the projection
        // of the map's CRS, then scales it according to `zoom` and the CRS's
        // `Transformation`. The result is pixel coordinate relative to
        // the CRS origin.
        project: function(latlng, zoom2) {
          zoom2 = zoom2 === void 0 ? this._zoom : zoom2;
          return this.options.crs.latLngToPoint(toLatLng(latlng), zoom2);
        },
        // @method unproject(point: Point, zoom: Number): LatLng
        // Inverse of [`project`](#map-project).
        unproject: function(point, zoom2) {
          zoom2 = zoom2 === void 0 ? this._zoom : zoom2;
          return this.options.crs.pointToLatLng(toPoint(point), zoom2);
        },
        // @method layerPointToLatLng(point: Point): LatLng
        // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
        // returns the corresponding geographical coordinate (for the current zoom level).
        layerPointToLatLng: function(point) {
          var projectedPoint = toPoint(point).add(this.getPixelOrigin());
          return this.unproject(projectedPoint);
        },
        // @method latLngToLayerPoint(latlng: LatLng): Point
        // Given a geographical coordinate, returns the corresponding pixel coordinate
        // relative to the [origin pixel](#map-getpixelorigin).
        latLngToLayerPoint: function(latlng) {
          var projectedPoint = this.project(toLatLng(latlng))._round();
          return projectedPoint._subtract(this.getPixelOrigin());
        },
        // @method wrapLatLng(latlng: LatLng): LatLng
        // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
        // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
        // CRS's bounds.
        // By default this means longitude is wrapped around the dateline so its
        // value is between -180 and +180 degrees.
        wrapLatLng: function(latlng) {
          return this.options.crs.wrapLatLng(toLatLng(latlng));
        },
        // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
        // Returns a `LatLngBounds` with the same size as the given one, ensuring that
        // its center is within the CRS's bounds.
        // By default this means the center longitude is wrapped around the dateline so its
        // value is between -180 and +180 degrees, and the majority of the bounds
        // overlaps the CRS's bounds.
        wrapLatLngBounds: function(latlng) {
          return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
        },
        // @method distance(latlng1: LatLng, latlng2: LatLng): Number
        // Returns the distance between two geographical coordinates according to
        // the map's CRS. By default this measures distance in meters.
        distance: function(latlng1, latlng2) {
          return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
        },
        // @method containerPointToLayerPoint(point: Point): Point
        // Given a pixel coordinate relative to the map container, returns the corresponding
        // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
        containerPointToLayerPoint: function(point) {
          return toPoint(point).subtract(this._getMapPanePos());
        },
        // @method layerPointToContainerPoint(point: Point): Point
        // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
        // returns the corresponding pixel coordinate relative to the map container.
        layerPointToContainerPoint: function(point) {
          return toPoint(point).add(this._getMapPanePos());
        },
        // @method containerPointToLatLng(point: Point): LatLng
        // Given a pixel coordinate relative to the map container, returns
        // the corresponding geographical coordinate (for the current zoom level).
        containerPointToLatLng: function(point) {
          var layerPoint = this.containerPointToLayerPoint(toPoint(point));
          return this.layerPointToLatLng(layerPoint);
        },
        // @method latLngToContainerPoint(latlng: LatLng): Point
        // Given a geographical coordinate, returns the corresponding pixel coordinate
        // relative to the map container.
        latLngToContainerPoint: function(latlng) {
          return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
        },
        // @method mouseEventToContainerPoint(ev: MouseEvent): Point
        // Given a MouseEvent object, returns the pixel coordinate relative to the
        // map container where the event took place.
        mouseEventToContainerPoint: function(e) {
          return getMousePosition(e, this._container);
        },
        // @method mouseEventToLayerPoint(ev: MouseEvent): Point
        // Given a MouseEvent object, returns the pixel coordinate relative to
        // the [origin pixel](#map-getpixelorigin) where the event took place.
        mouseEventToLayerPoint: function(e) {
          return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
        },
        // @method mouseEventToLatLng(ev: MouseEvent): LatLng
        // Given a MouseEvent object, returns geographical coordinate where the
        // event took place.
        mouseEventToLatLng: function(e) {
          return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
        },
        // map initialization methods
        _initContainer: function(id2) {
          var container = this._container = get3(id2);
          if (!container) {
            throw new Error("Map container not found.");
          } else if (container._leaflet_id) {
            throw new Error("Map container is already initialized.");
          }
          on(container, "scroll", this._onScroll, this);
          this._containerId = stamp(container);
        },
        _initLayout: function() {
          var container = this._container;
          this._fadeAnimated = this.options.fadeAnimation && Browser.any3d;
          addClass(container, "leaflet-container" + (Browser.touch ? " leaflet-touch" : "") + (Browser.retina ? " leaflet-retina" : "") + (Browser.ielt9 ? " leaflet-oldie" : "") + (Browser.safari ? " leaflet-safari" : "") + (this._fadeAnimated ? " leaflet-fade-anim" : ""));
          var position = getStyle(container, "position");
          if (position !== "absolute" && position !== "relative" && position !== "fixed" && position !== "sticky") {
            container.style.position = "relative";
          }
          this._initPanes();
          if (this._initControlPos) {
            this._initControlPos();
          }
        },
        _initPanes: function() {
          var panes = this._panes = {};
          this._paneRenderers = {};
          this._mapPane = this.createPane("mapPane", this._container);
          setPosition(this._mapPane, new Point(0, 0));
          this.createPane("tilePane");
          this.createPane("overlayPane");
          this.createPane("shadowPane");
          this.createPane("markerPane");
          this.createPane("tooltipPane");
          this.createPane("popupPane");
          if (!this.options.markerZoomAnimation) {
            addClass(panes.markerPane, "leaflet-zoom-hide");
            addClass(panes.shadowPane, "leaflet-zoom-hide");
          }
        },
        // private methods that modify map state
        // @section Map state change events
        _resetView: function(center2, zoom2, noMoveStart) {
          setPosition(this._mapPane, new Point(0, 0));
          var loading = !this._loaded;
          this._loaded = true;
          zoom2 = this._limitZoom(zoom2);
          this.fire("viewprereset");
          var zoomChanged = this._zoom !== zoom2;
          this._moveStart(zoomChanged, noMoveStart)._move(center2, zoom2)._moveEnd(zoomChanged);
          this.fire("viewreset");
          if (loading) {
            this.fire("load");
          }
        },
        _moveStart: function(zoomChanged, noMoveStart) {
          if (zoomChanged) {
            this.fire("zoomstart");
          }
          if (!noMoveStart) {
            this.fire("movestart");
          }
          return this;
        },
        _move: function(center2, zoom2, data, supressEvent) {
          if (zoom2 === void 0) {
            zoom2 = this._zoom;
          }
          var zoomChanged = this._zoom !== zoom2;
          this._zoom = zoom2;
          this._lastCenter = center2;
          this._pixelOrigin = this._getNewPixelOrigin(center2);
          if (!supressEvent) {
            if (zoomChanged || data && data.pinch) {
              this.fire("zoom", data);
            }
            this.fire("move", data);
          } else if (data && data.pinch) {
            this.fire("zoom", data);
          }
          return this;
        },
        _moveEnd: function(zoomChanged) {
          if (zoomChanged) {
            this.fire("zoomend");
          }
          return this.fire("moveend");
        },
        _stop: function() {
          cancelAnimFrame(this._flyToFrame);
          if (this._panAnim) {
            this._panAnim.stop();
          }
          return this;
        },
        _rawPanBy: function(offset2) {
          setPosition(this._mapPane, this._getMapPanePos().subtract(offset2));
        },
        _getZoomSpan: function() {
          return this.getMaxZoom() - this.getMinZoom();
        },
        _panInsideMaxBounds: function() {
          if (!this._enforcingBounds) {
            this.panInsideBounds(this.options.maxBounds);
          }
        },
        _checkIfLoaded: function() {
          if (!this._loaded) {
            throw new Error("Set map center and zoom first.");
          }
        },
        // DOM event handling
        // @section Interaction events
        _initEvents: function(remove3) {
          this._targets = {};
          this._targets[stamp(this._container)] = this;
          var onOff = remove3 ? off : on;
          onOff(this._container, "click dblclick mousedown mouseup mouseover mouseout mousemove contextmenu keypress keydown keyup", this._handleDOMEvent, this);
          if (this.options.trackResize) {
            onOff(window, "resize", this._onResize, this);
          }
          if (Browser.any3d && this.options.transform3DLimit) {
            (remove3 ? this.off : this.on).call(this, "moveend", this._onMoveEnd);
          }
        },
        _onResize: function() {
          cancelAnimFrame(this._resizeRequest);
          this._resizeRequest = requestAnimFrame(
            function() {
              this.invalidateSize({ debounceMoveend: true });
            },
            this
          );
        },
        _onScroll: function() {
          this._container.scrollTop = 0;
          this._container.scrollLeft = 0;
        },
        _onMoveEnd: function() {
          var pos = this._getMapPanePos();
          if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
            this._resetView(this.getCenter(), this.getZoom());
          }
        },
        _findEventTargets: function(e, type) {
          var targets = [], target, isHover = type === "mouseout" || type === "mouseover", src = e.target || e.srcElement, dragging = false;
          while (src) {
            target = this._targets[stamp(src)];
            if (target && (type === "click" || type === "preclick") && this._draggableMoved(target)) {
              dragging = true;
              break;
            }
            if (target && target.listens(type, true)) {
              if (isHover && !isExternalTarget(src, e)) {
                break;
              }
              targets.push(target);
              if (isHover) {
                break;
              }
            }
            if (src === this._container) {
              break;
            }
            src = src.parentNode;
          }
          if (!targets.length && !dragging && !isHover && this.listens(type, true)) {
            targets = [this];
          }
          return targets;
        },
        _isClickDisabled: function(el) {
          while (el && el !== this._container) {
            if (el["_leaflet_disable_click"]) {
              return true;
            }
            el = el.parentNode;
          }
        },
        _handleDOMEvent: function(e) {
          var el = e.target || e.srcElement;
          if (!this._loaded || el["_leaflet_disable_events"] || e.type === "click" && this._isClickDisabled(el)) {
            return;
          }
          var type = e.type;
          if (type === "mousedown") {
            preventOutline(el);
          }
          this._fireDOMEvent(e, type);
        },
        _mouseEvents: ["click", "dblclick", "mouseover", "mouseout", "contextmenu"],
        _fireDOMEvent: function(e, type, canvasTargets) {
          if (e.type === "click") {
            var synth = extend3({}, e);
            synth.type = "preclick";
            this._fireDOMEvent(synth, synth.type, canvasTargets);
          }
          var targets = this._findEventTargets(e, type);
          if (canvasTargets) {
            var filtered = [];
            for (var i = 0; i < canvasTargets.length; i++) {
              if (canvasTargets[i].listens(type, true)) {
                filtered.push(canvasTargets[i]);
              }
            }
            targets = filtered.concat(targets);
          }
          if (!targets.length) {
            return;
          }
          if (type === "contextmenu") {
            preventDefault(e);
          }
          var target = targets[0];
          var data = {
            originalEvent: e
          };
          if (e.type !== "keypress" && e.type !== "keydown" && e.type !== "keyup") {
            var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
            data.containerPoint = isMarker ? this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
            data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
            data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
          }
          for (i = 0; i < targets.length; i++) {
            targets[i].fire(type, data, true);
            if (data.originalEvent._stopped || targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1) {
              return;
            }
          }
        },
        _draggableMoved: function(obj) {
          obj = obj.dragging && obj.dragging.enabled() ? obj : this;
          return obj.dragging && obj.dragging.moved() || this.boxZoom && this.boxZoom.moved();
        },
        _clearHandlers: function() {
          for (var i = 0, len = this._handlers.length; i < len; i++) {
            this._handlers[i].disable();
          }
        },
        // @section Other Methods
        // @method whenReady(fn: Function, context?: Object): this
        // Runs the given function `fn` when the map gets initialized with
        // a view (center and zoom) and at least one layer, or immediately
        // if it's already initialized, optionally passing a function context.
        whenReady: function(callback, context) {
          if (this._loaded) {
            callback.call(context || this, { target: this });
          } else {
            this.on("load", callback, context);
          }
          return this;
        },
        // private methods for getting map state
        _getMapPanePos: function() {
          return getPosition(this._mapPane) || new Point(0, 0);
        },
        _moved: function() {
          var pos = this._getMapPanePos();
          return pos && !pos.equals([0, 0]);
        },
        _getTopLeftPoint: function(center2, zoom2) {
          var pixelOrigin = center2 && zoom2 !== void 0 ? this._getNewPixelOrigin(center2, zoom2) : this.getPixelOrigin();
          return pixelOrigin.subtract(this._getMapPanePos());
        },
        _getNewPixelOrigin: function(center2, zoom2) {
          var viewHalf = this.getSize()._divideBy(2);
          return this.project(center2, zoom2)._subtract(viewHalf)._add(this._getMapPanePos())._round();
        },
        _latLngToNewLayerPoint: function(latlng, zoom2, center2) {
          var topLeft = this._getNewPixelOrigin(center2, zoom2);
          return this.project(latlng, zoom2)._subtract(topLeft);
        },
        _latLngBoundsToNewLayerBounds: function(latLngBounds, zoom2, center2) {
          var topLeft = this._getNewPixelOrigin(center2, zoom2);
          return toBounds([
            this.project(latLngBounds.getSouthWest(), zoom2)._subtract(topLeft),
            this.project(latLngBounds.getNorthWest(), zoom2)._subtract(topLeft),
            this.project(latLngBounds.getSouthEast(), zoom2)._subtract(topLeft),
            this.project(latLngBounds.getNorthEast(), zoom2)._subtract(topLeft)
          ]);
        },
        // layer point of the current center
        _getCenterLayerPoint: function() {
          return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
        },
        // offset of the specified place to the current center in pixels
        _getCenterOffset: function(latlng) {
          return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
        },
        // adjust center for view to get inside bounds
        _limitCenter: function(center2, zoom2, bounds) {
          if (!bounds) {
            return center2;
          }
          var centerPoint = this.project(center2, zoom2), viewHalf = this.getSize().divideBy(2), viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)), offset2 = this._getBoundsOffset(viewBounds, bounds, zoom2);
          if (Math.abs(offset2.x) <= 1 && Math.abs(offset2.y) <= 1) {
            return center2;
          }
          return this.unproject(centerPoint.add(offset2), zoom2);
        },
        // adjust offset for view to get inside bounds
        _limitOffset: function(offset2, bounds) {
          if (!bounds) {
            return offset2;
          }
          var viewBounds = this.getPixelBounds(), newBounds = new Bounds(viewBounds.min.add(offset2), viewBounds.max.add(offset2));
          return offset2.add(this._getBoundsOffset(newBounds, bounds));
        },
        // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
        _getBoundsOffset: function(pxBounds, maxBounds, zoom2) {
          var projectedMaxBounds = toBounds(
            this.project(maxBounds.getNorthEast(), zoom2),
            this.project(maxBounds.getSouthWest(), zoom2)
          ), minOffset = projectedMaxBounds.min.subtract(pxBounds.min), maxOffset = projectedMaxBounds.max.subtract(pxBounds.max), dx = this._rebound(minOffset.x, -maxOffset.x), dy = this._rebound(minOffset.y, -maxOffset.y);
          return new Point(dx, dy);
        },
        _rebound: function(left2, right2) {
          return left2 + right2 > 0 ? Math.round(left2 - right2) / 2 : Math.max(0, Math.ceil(left2)) - Math.max(0, Math.floor(right2));
        },
        _limitZoom: function(zoom2) {
          var min = this.getMinZoom(), max = this.getMaxZoom(), snap = Browser.any3d ? this.options.zoomSnap : 1;
          if (snap) {
            zoom2 = Math.round(zoom2 / snap) * snap;
          }
          return Math.max(min, Math.min(max, zoom2));
        },
        _onPanTransitionStep: function() {
          this.fire("move");
        },
        _onPanTransitionEnd: function() {
          removeClass(this._mapPane, "leaflet-pan-anim");
          this.fire("moveend");
        },
        _tryAnimatedPan: function(center2, options) {
          var offset2 = this._getCenterOffset(center2)._trunc();
          if ((options && options.animate) !== true && !this.getSize().contains(offset2)) {
            return false;
          }
          this.panBy(offset2, options);
          return true;
        },
        _createAnimProxy: function() {
          var proxy = this._proxy = create$1("div", "leaflet-proxy leaflet-zoom-animated");
          this._panes.mapPane.appendChild(proxy);
          this.on("zoomanim", function(e) {
            var prop = TRANSFORM, transform2 = this._proxy.style[prop];
            setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
            if (transform2 === this._proxy.style[prop] && this._animatingZoom) {
              this._onZoomTransitionEnd();
            }
          }, this);
          this.on("load moveend", this._animMoveEnd, this);
          this._on("unload", this._destroyAnimProxy, this);
        },
        _destroyAnimProxy: function() {
          remove2(this._proxy);
          this.off("load moveend", this._animMoveEnd, this);
          delete this._proxy;
        },
        _animMoveEnd: function() {
          var c = this.getCenter(), z2 = this.getZoom();
          setTransform(this._proxy, this.project(c, z2), this.getZoomScale(z2, 1));
        },
        _catchTransitionEnd: function(e) {
          if (this._animatingZoom && e.propertyName.indexOf("transform") >= 0) {
            this._onZoomTransitionEnd();
          }
        },
        _nothingToAnimate: function() {
          return !this._container.getElementsByClassName("leaflet-zoom-animated").length;
        },
        _tryAnimatedZoom: function(center2, zoom2, options) {
          if (this._animatingZoom) {
            return true;
          }
          options = options || {};
          if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() || Math.abs(zoom2 - this._zoom) > this.options.zoomAnimationThreshold) {
            return false;
          }
          var scale2 = this.getZoomScale(zoom2), offset2 = this._getCenterOffset(center2)._divideBy(1 - 1 / scale2);
          if (options.animate !== true && !this.getSize().contains(offset2)) {
            return false;
          }
          requestAnimFrame(function() {
            this._moveStart(true, options.noMoveStart || false)._animateZoom(center2, zoom2, true);
          }, this);
          return true;
        },
        _animateZoom: function(center2, zoom2, startAnim, noUpdate) {
          if (!this._mapPane) {
            return;
          }
          if (startAnim) {
            this._animatingZoom = true;
            this._animateToCenter = center2;
            this._animateToZoom = zoom2;
            addClass(this._mapPane, "leaflet-zoom-anim");
          }
          this.fire("zoomanim", {
            center: center2,
            zoom: zoom2,
            noUpdate
          });
          if (!this._tempFireZoomEvent) {
            this._tempFireZoomEvent = this._zoom !== this._animateToZoom;
          }
          this._move(this._animateToCenter, this._animateToZoom, void 0, true);
          setTimeout(bind(this._onZoomTransitionEnd, this), 250);
        },
        _onZoomTransitionEnd: function() {
          if (!this._animatingZoom) {
            return;
          }
          if (this._mapPane) {
            removeClass(this._mapPane, "leaflet-zoom-anim");
          }
          this._animatingZoom = false;
          this._move(this._animateToCenter, this._animateToZoom, void 0, true);
          if (this._tempFireZoomEvent) {
            this.fire("zoom");
          }
          delete this._tempFireZoomEvent;
          this.fire("move");
          this._moveEnd(true);
        }
      });
      function createMap(id2, options) {
        return new Map2(id2, options);
      }
      var Control = Class2.extend({
        // @section
        // @aka Control Options
        options: {
          // @option position: String = 'topright'
          // The position of the control (one of the map corners). Possible values are `'topleft'`,
          // `'topright'`, `'bottomleft'` or `'bottomright'`
          position: "topright"
        },
        initialize: function(options) {
          setOptions(this, options);
        },
        /* @section
         * Classes extending L.Control will inherit the following methods:
         *
         * @method getPosition: string
         * Returns the position of the control.
         */
        getPosition: function() {
          return this.options.position;
        },
        // @method setPosition(position: string): this
        // Sets the position of the control.
        setPosition: function(position) {
          var map4 = this._map;
          if (map4) {
            map4.removeControl(this);
          }
          this.options.position = position;
          if (map4) {
            map4.addControl(this);
          }
          return this;
        },
        // @method getContainer: HTMLElement
        // Returns the HTMLElement that contains the control.
        getContainer: function() {
          return this._container;
        },
        // @method addTo(map: Map): this
        // Adds the control to the given map.
        addTo: function(map4) {
          this.remove();
          this._map = map4;
          var container = this._container = this.onAdd(map4), pos = this.getPosition(), corner = map4._controlCorners[pos];
          addClass(container, "leaflet-control");
          if (pos.indexOf("bottom") !== -1) {
            corner.insertBefore(container, corner.firstChild);
          } else {
            corner.appendChild(container);
          }
          this._map.on("unload", this.remove, this);
          return this;
        },
        // @method remove: this
        // Removes the control from the map it is currently active on.
        remove: function() {
          if (!this._map) {
            return this;
          }
          remove2(this._container);
          if (this.onRemove) {
            this.onRemove(this._map);
          }
          this._map.off("unload", this.remove, this);
          this._map = null;
          return this;
        },
        _refocusOnMap: function(e) {
          if (this._map && e && e.screenX > 0 && e.screenY > 0) {
            this._map.getContainer().focus();
          }
        }
      });
      var control = function(options) {
        return new Control(options);
      };
      Map2.include({
        // @method addControl(control: Control): this
        // Adds the given control to the map
        addControl: function(control2) {
          control2.addTo(this);
          return this;
        },
        // @method removeControl(control: Control): this
        // Removes the given control from the map
        removeControl: function(control2) {
          control2.remove();
          return this;
        },
        _initControlPos: function() {
          var corners = this._controlCorners = {}, l2 = "leaflet-", container = this._controlContainer = create$1("div", l2 + "control-container", this._container);
          function createCorner(vSide, hSide) {
            var className = l2 + vSide + " " + l2 + hSide;
            corners[vSide + hSide] = create$1("div", className, container);
          }
          createCorner("top", "left");
          createCorner("top", "right");
          createCorner("bottom", "left");
          createCorner("bottom", "right");
        },
        _clearControlPos: function() {
          for (var i in this._controlCorners) {
            remove2(this._controlCorners[i]);
          }
          remove2(this._controlContainer);
          delete this._controlCorners;
          delete this._controlContainer;
        }
      });
      var Layers = Control.extend({
        // @section
        // @aka Control.Layers options
        options: {
          // @option collapsed: Boolean = true
          // If `true`, the control will be collapsed into an icon and expanded on mouse hover, touch, or keyboard activation.
          collapsed: true,
          position: "topright",
          // @option autoZIndex: Boolean = true
          // If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.
          autoZIndex: true,
          // @option hideSingleBase: Boolean = false
          // If `true`, the base layers in the control will be hidden when there is only one.
          hideSingleBase: false,
          // @option sortLayers: Boolean = false
          // Whether to sort the layers. When `false`, layers will keep the order
          // in which they were added to the control.
          sortLayers: false,
          // @option sortFunction: Function = *
          // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
          // that will be used for sorting the layers, when `sortLayers` is `true`.
          // The function receives both the `L.Layer` instances and their names, as in
          // `sortFunction(layerA, layerB, nameA, nameB)`.
          // By default, it sorts layers alphabetically by their name.
          sortFunction: function(layerA, layerB, nameA, nameB) {
            return nameA < nameB ? -1 : nameB < nameA ? 1 : 0;
          }
        },
        initialize: function(baseLayers, overlays, options) {
          setOptions(this, options);
          this._layerControlInputs = [];
          this._layers = [];
          this._lastZIndex = 0;
          this._handlingClick = false;
          this._preventClick = false;
          for (var i in baseLayers) {
            this._addLayer(baseLayers[i], i);
          }
          for (i in overlays) {
            this._addLayer(overlays[i], i, true);
          }
        },
        onAdd: function(map4) {
          this._initLayout();
          this._update();
          this._map = map4;
          map4.on("zoomend", this._checkDisabledLayers, this);
          for (var i = 0; i < this._layers.length; i++) {
            this._layers[i].layer.on("add remove", this._onLayerChange, this);
          }
          return this._container;
        },
        addTo: function(map4) {
          Control.prototype.addTo.call(this, map4);
          return this._expandIfNotCollapsed();
        },
        onRemove: function() {
          this._map.off("zoomend", this._checkDisabledLayers, this);
          for (var i = 0; i < this._layers.length; i++) {
            this._layers[i].layer.off("add remove", this._onLayerChange, this);
          }
        },
        // @method addBaseLayer(layer: Layer, name: String): this
        // Adds a base layer (radio button entry) with the given name to the control.
        addBaseLayer: function(layer, name) {
          this._addLayer(layer, name);
          return this._map ? this._update() : this;
        },
        // @method addOverlay(layer: Layer, name: String): this
        // Adds an overlay (checkbox entry) with the given name to the control.
        addOverlay: function(layer, name) {
          this._addLayer(layer, name, true);
          return this._map ? this._update() : this;
        },
        // @method removeLayer(layer: Layer): this
        // Remove the given layer from the control.
        removeLayer: function(layer) {
          layer.off("add remove", this._onLayerChange, this);
          var obj = this._getLayer(stamp(layer));
          if (obj) {
            this._layers.splice(this._layers.indexOf(obj), 1);
          }
          return this._map ? this._update() : this;
        },
        // @method expand(): this
        // Expand the control container if collapsed.
        expand: function() {
          addClass(this._container, "leaflet-control-layers-expanded");
          this._section.style.height = null;
          var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
          if (acceptableHeight < this._section.clientHeight) {
            addClass(this._section, "leaflet-control-layers-scrollbar");
            this._section.style.height = acceptableHeight + "px";
          } else {
            removeClass(this._section, "leaflet-control-layers-scrollbar");
          }
          this._checkDisabledLayers();
          return this;
        },
        // @method collapse(): this
        // Collapse the control container if expanded.
        collapse: function() {
          removeClass(this._container, "leaflet-control-layers-expanded");
          return this;
        },
        _initLayout: function() {
          var className = "leaflet-control-layers", container = this._container = create$1("div", className), collapsed = this.options.collapsed;
          container.setAttribute("aria-haspopup", true);
          disableClickPropagation(container);
          disableScrollPropagation(container);
          var section = this._section = create$1("section", className + "-list");
          if (collapsed) {
            this._map.on("click", this.collapse, this);
            on(container, {
              mouseenter: this._expandSafely,
              mouseleave: this.collapse
            }, this);
          }
          var link = this._layersLink = create$1("a", className + "-toggle", container);
          link.href = "#";
          link.title = "Layers";
          link.setAttribute("role", "button");
          on(link, {
            keydown: function(e) {
              if (e.keyCode === 13) {
                this._expandSafely();
              }
            },
            // Certain screen readers intercept the key event and instead send a click event
            click: function(e) {
              preventDefault(e);
              this._expandSafely();
            }
          }, this);
          if (!collapsed) {
            this.expand();
          }
          this._baseLayersList = create$1("div", className + "-base", section);
          this._separator = create$1("div", className + "-separator", section);
          this._overlaysList = create$1("div", className + "-overlays", section);
          container.appendChild(section);
        },
        _getLayer: function(id2) {
          for (var i = 0; i < this._layers.length; i++) {
            if (this._layers[i] && stamp(this._layers[i].layer) === id2) {
              return this._layers[i];
            }
          }
        },
        _addLayer: function(layer, name, overlay) {
          if (this._map) {
            layer.on("add remove", this._onLayerChange, this);
          }
          this._layers.push({
            layer,
            name,
            overlay
          });
          if (this.options.sortLayers) {
            this._layers.sort(bind(function(a, b) {
              return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
            }, this));
          }
          if (this.options.autoZIndex && layer.setZIndex) {
            this._lastZIndex++;
            layer.setZIndex(this._lastZIndex);
          }
          this._expandIfNotCollapsed();
        },
        _update: function() {
          if (!this._container) {
            return this;
          }
          empty2(this._baseLayersList);
          empty2(this._overlaysList);
          this._layerControlInputs = [];
          var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
          for (i = 0; i < this._layers.length; i++) {
            obj = this._layers[i];
            this._addItem(obj);
            overlaysPresent = overlaysPresent || obj.overlay;
            baseLayersPresent = baseLayersPresent || !obj.overlay;
            baseLayersCount += !obj.overlay ? 1 : 0;
          }
          if (this.options.hideSingleBase) {
            baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
            this._baseLayersList.style.display = baseLayersPresent ? "" : "none";
          }
          this._separator.style.display = overlaysPresent && baseLayersPresent ? "" : "none";
          return this;
        },
        _onLayerChange: function(e) {
          if (!this._handlingClick) {
            this._update();
          }
          var obj = this._getLayer(stamp(e.target));
          var type = obj.overlay ? e.type === "add" ? "overlayadd" : "overlayremove" : e.type === "add" ? "baselayerchange" : null;
          if (type) {
            this._map.fire(type, obj);
          }
        },
        // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see https://stackoverflow.com/a/119079)
        _createRadioElement: function(name, checked) {
          var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"' + (checked ? ' checked="checked"' : "") + "/>";
          var radioFragment = document.createElement("div");
          radioFragment.innerHTML = radioHtml;
          return radioFragment.firstChild;
        },
        _addItem: function(obj) {
          var label = document.createElement("label"), checked = this._map.hasLayer(obj.layer), input;
          if (obj.overlay) {
            input = document.createElement("input");
            input.type = "checkbox";
            input.className = "leaflet-control-layers-selector";
            input.defaultChecked = checked;
          } else {
            input = this._createRadioElement("leaflet-base-layers_" + stamp(this), checked);
          }
          this._layerControlInputs.push(input);
          input.layerId = stamp(obj.layer);
          on(input, "click", this._onInputClick, this);
          var name = document.createElement("span");
          name.innerHTML = " " + obj.name;
          var holder = document.createElement("span");
          label.appendChild(holder);
          holder.appendChild(input);
          holder.appendChild(name);
          var container = obj.overlay ? this._overlaysList : this._baseLayersList;
          container.appendChild(label);
          this._checkDisabledLayers();
          return label;
        },
        _onInputClick: function() {
          if (this._preventClick) {
            return;
          }
          var inputs = this._layerControlInputs, input, layer;
          var addedLayers = [], removedLayers = [];
          this._handlingClick = true;
          for (var i = inputs.length - 1; i >= 0; i--) {
            input = inputs[i];
            layer = this._getLayer(input.layerId).layer;
            if (input.checked) {
              addedLayers.push(layer);
            } else if (!input.checked) {
              removedLayers.push(layer);
            }
          }
          for (i = 0; i < removedLayers.length; i++) {
            if (this._map.hasLayer(removedLayers[i])) {
              this._map.removeLayer(removedLayers[i]);
            }
          }
          for (i = 0; i < addedLayers.length; i++) {
            if (!this._map.hasLayer(addedLayers[i])) {
              this._map.addLayer(addedLayers[i]);
            }
          }
          this._handlingClick = false;
          this._refocusOnMap();
        },
        _checkDisabledLayers: function() {
          var inputs = this._layerControlInputs, input, layer, zoom2 = this._map.getZoom();
          for (var i = inputs.length - 1; i >= 0; i--) {
            input = inputs[i];
            layer = this._getLayer(input.layerId).layer;
            input.disabled = layer.options.minZoom !== void 0 && zoom2 < layer.options.minZoom || layer.options.maxZoom !== void 0 && zoom2 > layer.options.maxZoom;
          }
        },
        _expandIfNotCollapsed: function() {
          if (this._map && !this.options.collapsed) {
            this.expand();
          }
          return this;
        },
        _expandSafely: function() {
          var section = this._section;
          this._preventClick = true;
          on(section, "click", preventDefault);
          this.expand();
          var that = this;
          setTimeout(function() {
            off(section, "click", preventDefault);
            that._preventClick = false;
          });
        }
      });
      var layers = function(baseLayers, overlays, options) {
        return new Layers(baseLayers, overlays, options);
      };
      var Zoom = Control.extend({
        // @section
        // @aka Control.Zoom options
        options: {
          position: "topleft",
          // @option zoomInText: String = '<span aria-hidden="true">+</span>'
          // The text set on the 'zoom in' button.
          zoomInText: '<span aria-hidden="true">+</span>',
          // @option zoomInTitle: String = 'Zoom in'
          // The title set on the 'zoom in' button.
          zoomInTitle: "Zoom in",
          // @option zoomOutText: String = '<span aria-hidden="true">&#x2212;</span>'
          // The text set on the 'zoom out' button.
          zoomOutText: '<span aria-hidden="true">&#x2212;</span>',
          // @option zoomOutTitle: String = 'Zoom out'
          // The title set on the 'zoom out' button.
          zoomOutTitle: "Zoom out"
        },
        onAdd: function(map4) {
          var zoomName = "leaflet-control-zoom", container = create$1("div", zoomName + " leaflet-bar"), options = this.options;
          this._zoomInButton = this._createButton(
            options.zoomInText,
            options.zoomInTitle,
            zoomName + "-in",
            container,
            this._zoomIn
          );
          this._zoomOutButton = this._createButton(
            options.zoomOutText,
            options.zoomOutTitle,
            zoomName + "-out",
            container,
            this._zoomOut
          );
          this._updateDisabled();
          map4.on("zoomend zoomlevelschange", this._updateDisabled, this);
          return container;
        },
        onRemove: function(map4) {
          map4.off("zoomend zoomlevelschange", this._updateDisabled, this);
        },
        disable: function() {
          this._disabled = true;
          this._updateDisabled();
          return this;
        },
        enable: function() {
          this._disabled = false;
          this._updateDisabled();
          return this;
        },
        _zoomIn: function(e) {
          if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
            this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
          }
        },
        _zoomOut: function(e) {
          if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
            this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
          }
        },
        _createButton: function(html, title, className, container, fn) {
          var link = create$1("a", className, container);
          link.innerHTML = html;
          link.href = "#";
          link.title = title;
          link.setAttribute("role", "button");
          link.setAttribute("aria-label", title);
          disableClickPropagation(link);
          on(link, "click", stop);
          on(link, "click", fn, this);
          on(link, "click", this._refocusOnMap, this);
          return link;
        },
        _updateDisabled: function() {
          var map4 = this._map, className = "leaflet-disabled";
          removeClass(this._zoomInButton, className);
          removeClass(this._zoomOutButton, className);
          this._zoomInButton.setAttribute("aria-disabled", "false");
          this._zoomOutButton.setAttribute("aria-disabled", "false");
          if (this._disabled || map4._zoom === map4.getMinZoom()) {
            addClass(this._zoomOutButton, className);
            this._zoomOutButton.setAttribute("aria-disabled", "true");
          }
          if (this._disabled || map4._zoom === map4.getMaxZoom()) {
            addClass(this._zoomInButton, className);
            this._zoomInButton.setAttribute("aria-disabled", "true");
          }
        }
      });
      Map2.mergeOptions({
        zoomControl: true
      });
      Map2.addInitHook(function() {
        if (this.options.zoomControl) {
          this.zoomControl = new Zoom();
          this.addControl(this.zoomControl);
        }
      });
      var zoom = function(options) {
        return new Zoom(options);
      };
      var Scale = Control.extend({
        // @section
        // @aka Control.Scale options
        options: {
          position: "bottomleft",
          // @option maxWidth: Number = 100
          // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
          maxWidth: 100,
          // @option metric: Boolean = True
          // Whether to show the metric scale line (m/km).
          metric: true,
          // @option imperial: Boolean = True
          // Whether to show the imperial scale line (mi/ft).
          imperial: true
          // @option updateWhenIdle: Boolean = false
          // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
        },
        onAdd: function(map4) {
          var className = "leaflet-control-scale", container = create$1("div", className), options = this.options;
          this._addScales(options, className + "-line", container);
          map4.on(options.updateWhenIdle ? "moveend" : "move", this._update, this);
          map4.whenReady(this._update, this);
          return container;
        },
        onRemove: function(map4) {
          map4.off(this.options.updateWhenIdle ? "moveend" : "move", this._update, this);
        },
        _addScales: function(options, className, container) {
          if (options.metric) {
            this._mScale = create$1("div", className, container);
          }
          if (options.imperial) {
            this._iScale = create$1("div", className, container);
          }
        },
        _update: function() {
          var map4 = this._map, y2 = map4.getSize().y / 2;
          var maxMeters = map4.distance(
            map4.containerPointToLatLng([0, y2]),
            map4.containerPointToLatLng([this.options.maxWidth, y2])
          );
          this._updateScales(maxMeters);
        },
        _updateScales: function(maxMeters) {
          if (this.options.metric && maxMeters) {
            this._updateMetric(maxMeters);
          }
          if (this.options.imperial && maxMeters) {
            this._updateImperial(maxMeters);
          }
        },
        _updateMetric: function(maxMeters) {
          var meters = this._getRoundNum(maxMeters), label = meters < 1e3 ? meters + " m" : meters / 1e3 + " km";
          this._updateScale(this._mScale, label, meters / maxMeters);
        },
        _updateImperial: function(maxMeters) {
          var maxFeet = maxMeters * 3.2808399, maxMiles, miles, feet;
          if (maxFeet > 5280) {
            maxMiles = maxFeet / 5280;
            miles = this._getRoundNum(maxMiles);
            this._updateScale(this._iScale, miles + " mi", miles / maxMiles);
          } else {
            feet = this._getRoundNum(maxFeet);
            this._updateScale(this._iScale, feet + " ft", feet / maxFeet);
          }
        },
        _updateScale: function(scale2, text, ratio) {
          scale2.style.width = Math.round(this.options.maxWidth * ratio) + "px";
          scale2.innerHTML = text;
        },
        _getRoundNum: function(num) {
          var pow102 = Math.pow(10, (Math.floor(num) + "").length - 1), d = num / pow102;
          d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
          return pow102 * d;
        }
      });
      var scale = function(options) {
        return new Scale(options);
      };
      var ukrainianFlag = '<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="12" height="8" viewBox="0 0 12 8" class="leaflet-attribution-flag"><path fill="#4C7BE1" d="M0 0h12v4H0z"/><path fill="#FFD500" d="M0 4h12v3H0z"/><path fill="#E0BC00" d="M0 7h12v1H0z"/></svg>';
      var Attribution = Control.extend({
        // @section
        // @aka Control.Attribution options
        options: {
          position: "bottomright",
          // @option prefix: String|false = 'Leaflet'
          // The HTML text shown before the attributions. Pass `false` to disable.
          prefix: '<a href="https://leafletjs.com" title="A JavaScript library for interactive maps">' + (Browser.inlineSvg ? ukrainianFlag + " " : "") + "Leaflet</a>"
        },
        initialize: function(options) {
          setOptions(this, options);
          this._attributions = {};
        },
        onAdd: function(map4) {
          map4.attributionControl = this;
          this._container = create$1("div", "leaflet-control-attribution");
          disableClickPropagation(this._container);
          for (var i in map4._layers) {
            if (map4._layers[i].getAttribution) {
              this.addAttribution(map4._layers[i].getAttribution());
            }
          }
          this._update();
          map4.on("layeradd", this._addAttribution, this);
          return this._container;
        },
        onRemove: function(map4) {
          map4.off("layeradd", this._addAttribution, this);
        },
        _addAttribution: function(ev) {
          if (ev.layer.getAttribution) {
            this.addAttribution(ev.layer.getAttribution());
            ev.layer.once("remove", function() {
              this.removeAttribution(ev.layer.getAttribution());
            }, this);
          }
        },
        // @method setPrefix(prefix: String|false): this
        // The HTML text shown before the attributions. Pass `false` to disable.
        setPrefix: function(prefix) {
          this.options.prefix = prefix;
          this._update();
          return this;
        },
        // @method addAttribution(text: String): this
        // Adds an attribution text (e.g. `'&copy; OpenStreetMap contributors'`).
        addAttribution: function(text) {
          if (!text) {
            return this;
          }
          if (!this._attributions[text]) {
            this._attributions[text] = 0;
          }
          this._attributions[text]++;
          this._update();
          return this;
        },
        // @method removeAttribution(text: String): this
        // Removes an attribution text.
        removeAttribution: function(text) {
          if (!text) {
            return this;
          }
          if (this._attributions[text]) {
            this._attributions[text]--;
            this._update();
          }
          return this;
        },
        _update: function() {
          if (!this._map) {
            return;
          }
          var attribs = [];
          for (var i in this._attributions) {
            if (this._attributions[i]) {
              attribs.push(i);
            }
          }
          var prefixAndAttribs = [];
          if (this.options.prefix) {
            prefixAndAttribs.push(this.options.prefix);
          }
          if (attribs.length) {
            prefixAndAttribs.push(attribs.join(", "));
          }
          this._container.innerHTML = prefixAndAttribs.join(' <span aria-hidden="true">|</span> ');
        }
      });
      Map2.mergeOptions({
        attributionControl: true
      });
      Map2.addInitHook(function() {
        if (this.options.attributionControl) {
          new Attribution().addTo(this);
        }
      });
      var attribution = function(options) {
        return new Attribution(options);
      };
      Control.Layers = Layers;
      Control.Zoom = Zoom;
      Control.Scale = Scale;
      Control.Attribution = Attribution;
      control.layers = layers;
      control.zoom = zoom;
      control.scale = scale;
      control.attribution = attribution;
      var Handler = Class2.extend({
        initialize: function(map4) {
          this._map = map4;
        },
        // @method enable(): this
        // Enables the handler
        enable: function() {
          if (this._enabled) {
            return this;
          }
          this._enabled = true;
          this.addHooks();
          return this;
        },
        // @method disable(): this
        // Disables the handler
        disable: function() {
          if (!this._enabled) {
            return this;
          }
          this._enabled = false;
          this.removeHooks();
          return this;
        },
        // @method enabled(): Boolean
        // Returns `true` if the handler is enabled
        enabled: function() {
          return !!this._enabled;
        }
        // @section Extension methods
        // Classes inheriting from `Handler` must implement the two following methods:
        // @method addHooks()
        // Called when the handler is enabled, should add event hooks.
        // @method removeHooks()
        // Called when the handler is disabled, should remove the event hooks added previously.
      });
      Handler.addTo = function(map4, name) {
        map4.addHandler(name, this);
        return this;
      };
      var Mixin = { Events };
      var START = Browser.touch ? "touchstart mousedown" : "mousedown";
      var Draggable = Evented.extend({
        options: {
          // @section
          // @aka Draggable options
          // @option clickTolerance: Number = 3
          // The max number of pixels a user can shift the mouse pointer during a click
          // for it to be considered a valid click (as opposed to a mouse drag).
          clickTolerance: 3
        },
        // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
        // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
        initialize: function(element, dragStartTarget, preventOutline2, options) {
          setOptions(this, options);
          this._element = element;
          this._dragStartTarget = dragStartTarget || element;
          this._preventOutline = preventOutline2;
        },
        // @method enable()
        // Enables the dragging ability
        enable: function() {
          if (this._enabled) {
            return;
          }
          on(this._dragStartTarget, START, this._onDown, this);
          this._enabled = true;
        },
        // @method disable()
        // Disables the dragging ability
        disable: function() {
          if (!this._enabled) {
            return;
          }
          if (Draggable._dragging === this) {
            this.finishDrag(true);
          }
          off(this._dragStartTarget, START, this._onDown, this);
          this._enabled = false;
          this._moved = false;
        },
        _onDown: function(e) {
          if (!this._enabled) {
            return;
          }
          this._moved = false;
          if (hasClass(this._element, "leaflet-zoom-anim")) {
            return;
          }
          if (e.touches && e.touches.length !== 1) {
            if (Draggable._dragging === this) {
              this.finishDrag();
            }
            return;
          }
          if (Draggable._dragging || e.shiftKey || e.which !== 1 && e.button !== 1 && !e.touches) {
            return;
          }
          Draggable._dragging = this;
          if (this._preventOutline) {
            preventOutline(this._element);
          }
          disableImageDrag();
          disableTextSelection();
          if (this._moving) {
            return;
          }
          this.fire("down");
          var first = e.touches ? e.touches[0] : e, sizedParent = getSizedParentNode(this._element);
          this._startPoint = new Point(first.clientX, first.clientY);
          this._startPos = getPosition(this._element);
          this._parentScale = getScale(sizedParent);
          var mouseevent = e.type === "mousedown";
          on(document, mouseevent ? "mousemove" : "touchmove", this._onMove, this);
          on(document, mouseevent ? "mouseup" : "touchend touchcancel", this._onUp, this);
        },
        _onMove: function(e) {
          if (!this._enabled) {
            return;
          }
          if (e.touches && e.touches.length > 1) {
            this._moved = true;
            return;
          }
          var first = e.touches && e.touches.length === 1 ? e.touches[0] : e, offset2 = new Point(first.clientX, first.clientY)._subtract(this._startPoint);
          if (!offset2.x && !offset2.y) {
            return;
          }
          if (Math.abs(offset2.x) + Math.abs(offset2.y) < this.options.clickTolerance) {
            return;
          }
          offset2.x /= this._parentScale.x;
          offset2.y /= this._parentScale.y;
          preventDefault(e);
          if (!this._moved) {
            this.fire("dragstart");
            this._moved = true;
            addClass(document.body, "leaflet-dragging");
            this._lastTarget = e.target || e.srcElement;
            if (window.SVGElementInstance && this._lastTarget instanceof window.SVGElementInstance) {
              this._lastTarget = this._lastTarget.correspondingUseElement;
            }
            addClass(this._lastTarget, "leaflet-drag-target");
          }
          this._newPos = this._startPos.add(offset2);
          this._moving = true;
          this._lastEvent = e;
          this._updatePosition();
        },
        _updatePosition: function() {
          var e = { originalEvent: this._lastEvent };
          this.fire("predrag", e);
          setPosition(this._element, this._newPos);
          this.fire("drag", e);
        },
        _onUp: function() {
          if (!this._enabled) {
            return;
          }
          this.finishDrag();
        },
        finishDrag: function(noInertia) {
          removeClass(document.body, "leaflet-dragging");
          if (this._lastTarget) {
            removeClass(this._lastTarget, "leaflet-drag-target");
            this._lastTarget = null;
          }
          off(document, "mousemove touchmove", this._onMove, this);
          off(document, "mouseup touchend touchcancel", this._onUp, this);
          enableImageDrag();
          enableTextSelection();
          var fireDragend = this._moved && this._moving;
          this._moving = false;
          Draggable._dragging = false;
          if (fireDragend) {
            this.fire("dragend", {
              noInertia,
              distance: this._newPos.distanceTo(this._startPos)
            });
          }
        }
      });
      function clipPolygon(points, bounds, round) {
        var clippedPoints, edges = [1, 4, 2, 8], i, j, k, a, b, len, edge2, p;
        for (i = 0, len = points.length; i < len; i++) {
          points[i]._code = _getBitCode(points[i], bounds);
        }
        for (k = 0; k < 4; k++) {
          edge2 = edges[k];
          clippedPoints = [];
          for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
            a = points[i];
            b = points[j];
            if (!(a._code & edge2)) {
              if (b._code & edge2) {
                p = _getEdgeIntersection(b, a, edge2, bounds, round);
                p._code = _getBitCode(p, bounds);
                clippedPoints.push(p);
              }
              clippedPoints.push(a);
            } else if (!(b._code & edge2)) {
              p = _getEdgeIntersection(b, a, edge2, bounds, round);
              p._code = _getBitCode(p, bounds);
              clippedPoints.push(p);
            }
          }
          points = clippedPoints;
        }
        return points;
      }
      function polygonCenter(latlngs, crs) {
        var i, j, p1, p2, f, area, x2, y2, center2;
        if (!latlngs || latlngs.length === 0) {
          throw new Error("latlngs not passed");
        }
        if (!isFlat(latlngs)) {
          console.warn("latlngs are not flat! Only the first ring will be used");
          latlngs = latlngs[0];
        }
        var centroidLatLng = toLatLng([0, 0]);
        var bounds = toLatLngBounds(latlngs);
        var areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());
        if (areaBounds < 1700) {
          centroidLatLng = centroid(latlngs);
        }
        var len = latlngs.length;
        var points = [];
        for (i = 0; i < len; i++) {
          var latlng = toLatLng(latlngs[i]);
          points.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));
        }
        area = x2 = y2 = 0;
        for (i = 0, j = len - 1; i < len; j = i++) {
          p1 = points[i];
          p2 = points[j];
          f = p1.y * p2.x - p2.y * p1.x;
          x2 += (p1.x + p2.x) * f;
          y2 += (p1.y + p2.y) * f;
          area += f * 3;
        }
        if (area === 0) {
          center2 = points[0];
        } else {
          center2 = [x2 / area, y2 / area];
        }
        var latlngCenter = crs.unproject(toPoint(center2));
        return toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);
      }
      function centroid(coords) {
        var latSum = 0;
        var lngSum = 0;
        var len = 0;
        for (var i = 0; i < coords.length; i++) {
          var latlng = toLatLng(coords[i]);
          latSum += latlng.lat;
          lngSum += latlng.lng;
          len++;
        }
        return toLatLng([latSum / len, lngSum / len]);
      }
      var PolyUtil = {
        __proto__: null,
        clipPolygon,
        polygonCenter,
        centroid
      };
      function simplify(points, tolerance) {
        if (!tolerance || !points.length) {
          return points.slice();
        }
        var sqTolerance = tolerance * tolerance;
        points = _reducePoints(points, sqTolerance);
        points = _simplifyDP(points, sqTolerance);
        return points;
      }
      function pointToSegmentDistance(p, p1, p2) {
        return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
      }
      function closestPointOnSegment(p, p1, p2) {
        return _sqClosestPointOnSegment(p, p1, p2);
      }
      function _simplifyDP(points, sqTolerance) {
        var len = points.length, ArrayConstructor = typeof Uint8Array !== "undefined" ? Uint8Array : Array, markers = new ArrayConstructor(len);
        markers[0] = markers[len - 1] = 1;
        _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
        var i, newPoints = [];
        for (i = 0; i < len; i++) {
          if (markers[i]) {
            newPoints.push(points[i]);
          }
        }
        return newPoints;
      }
      function _simplifyDPStep(points, markers, sqTolerance, first, last) {
        var maxSqDist = 0, index2, i, sqDist;
        for (i = first + 1; i <= last - 1; i++) {
          sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
          if (sqDist > maxSqDist) {
            index2 = i;
            maxSqDist = sqDist;
          }
        }
        if (maxSqDist > sqTolerance) {
          markers[index2] = 1;
          _simplifyDPStep(points, markers, sqTolerance, first, index2);
          _simplifyDPStep(points, markers, sqTolerance, index2, last);
        }
      }
      function _reducePoints(points, sqTolerance) {
        var reducedPoints = [points[0]];
        for (var i = 1, prev = 0, len = points.length; i < len; i++) {
          if (_sqDist(points[i], points[prev]) > sqTolerance) {
            reducedPoints.push(points[i]);
            prev = i;
          }
        }
        if (prev < len - 1) {
          reducedPoints.push(points[len - 1]);
        }
        return reducedPoints;
      }
      var _lastCode;
      function clipSegment(a, b, bounds, useLastCode, round) {
        var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds), codeB = _getBitCode(b, bounds), codeOut, p, newCode;
        _lastCode = codeB;
        while (true) {
          if (!(codeA | codeB)) {
            return [a, b];
          }
          if (codeA & codeB) {
            return false;
          }
          codeOut = codeA || codeB;
          p = _getEdgeIntersection(a, b, codeOut, bounds, round);
          newCode = _getBitCode(p, bounds);
          if (codeOut === codeA) {
            a = p;
            codeA = newCode;
          } else {
            b = p;
            codeB = newCode;
          }
        }
      }
      function _getEdgeIntersection(a, b, code, bounds, round) {
        var dx = b.x - a.x, dy = b.y - a.y, min = bounds.min, max = bounds.max, x2, y2;
        if (code & 8) {
          x2 = a.x + dx * (max.y - a.y) / dy;
          y2 = max.y;
        } else if (code & 4) {
          x2 = a.x + dx * (min.y - a.y) / dy;
          y2 = min.y;
        } else if (code & 2) {
          x2 = max.x;
          y2 = a.y + dy * (max.x - a.x) / dx;
        } else if (code & 1) {
          x2 = min.x;
          y2 = a.y + dy * (min.x - a.x) / dx;
        }
        return new Point(x2, y2, round);
      }
      function _getBitCode(p, bounds) {
        var code = 0;
        if (p.x < bounds.min.x) {
          code |= 1;
        } else if (p.x > bounds.max.x) {
          code |= 2;
        }
        if (p.y < bounds.min.y) {
          code |= 4;
        } else if (p.y > bounds.max.y) {
          code |= 8;
        }
        return code;
      }
      function _sqDist(p1, p2) {
        var dx = p2.x - p1.x, dy = p2.y - p1.y;
        return dx * dx + dy * dy;
      }
      function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
        var x2 = p1.x, y2 = p1.y, dx = p2.x - x2, dy = p2.y - y2, dot = dx * dx + dy * dy, t;
        if (dot > 0) {
          t = ((p.x - x2) * dx + (p.y - y2) * dy) / dot;
          if (t > 1) {
            x2 = p2.x;
            y2 = p2.y;
          } else if (t > 0) {
            x2 += dx * t;
            y2 += dy * t;
          }
        }
        dx = p.x - x2;
        dy = p.y - y2;
        return sqDist ? dx * dx + dy * dy : new Point(x2, y2);
      }
      function isFlat(latlngs) {
        return !isArray(latlngs[0]) || typeof latlngs[0][0] !== "object" && typeof latlngs[0][0] !== "undefined";
      }
      function _flat(latlngs) {
        console.warn("Deprecated use of _flat, please use L.LineUtil.isFlat instead.");
        return isFlat(latlngs);
      }
      function polylineCenter(latlngs, crs) {
        var i, halfDist, segDist, dist, p1, p2, ratio, center2;
        if (!latlngs || latlngs.length === 0) {
          throw new Error("latlngs not passed");
        }
        if (!isFlat(latlngs)) {
          console.warn("latlngs are not flat! Only the first ring will be used");
          latlngs = latlngs[0];
        }
        var centroidLatLng = toLatLng([0, 0]);
        var bounds = toLatLngBounds(latlngs);
        var areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());
        if (areaBounds < 1700) {
          centroidLatLng = centroid(latlngs);
        }
        var len = latlngs.length;
        var points = [];
        for (i = 0; i < len; i++) {
          var latlng = toLatLng(latlngs[i]);
          points.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));
        }
        for (i = 0, halfDist = 0; i < len - 1; i++) {
          halfDist += points[i].distanceTo(points[i + 1]) / 2;
        }
        if (halfDist === 0) {
          center2 = points[0];
        } else {
          for (i = 0, dist = 0; i < len - 1; i++) {
            p1 = points[i];
            p2 = points[i + 1];
            segDist = p1.distanceTo(p2);
            dist += segDist;
            if (dist > halfDist) {
              ratio = (dist - halfDist) / segDist;
              center2 = [
                p2.x - ratio * (p2.x - p1.x),
                p2.y - ratio * (p2.y - p1.y)
              ];
              break;
            }
          }
        }
        var latlngCenter = crs.unproject(toPoint(center2));
        return toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);
      }
      var LineUtil = {
        __proto__: null,
        simplify,
        pointToSegmentDistance,
        closestPointOnSegment,
        clipSegment,
        _getEdgeIntersection,
        _getBitCode,
        _sqClosestPointOnSegment,
        isFlat,
        _flat,
        polylineCenter
      };
      var LonLat = {
        project: function(latlng) {
          return new Point(latlng.lng, latlng.lat);
        },
        unproject: function(point) {
          return new LatLng(point.y, point.x);
        },
        bounds: new Bounds([-180, -90], [180, 90])
      };
      var Mercator = {
        R: 6378137,
        R_MINOR: 6356752314245179e-9,
        bounds: new Bounds([-2003750834279e-5, -1549657073972e-5], [2003750834279e-5, 1876465623138e-5]),
        project: function(latlng) {
          var d = Math.PI / 180, r = this.R, y2 = latlng.lat * d, tmp = this.R_MINOR / r, e = Math.sqrt(1 - tmp * tmp), con = e * Math.sin(y2);
          var ts = Math.tan(Math.PI / 4 - y2 / 2) / Math.pow((1 - con) / (1 + con), e / 2);
          y2 = -r * Math.log(Math.max(ts, 1e-10));
          return new Point(latlng.lng * d * r, y2);
        },
        unproject: function(point) {
          var d = 180 / Math.PI, r = this.R, tmp = this.R_MINOR / r, e = Math.sqrt(1 - tmp * tmp), ts = Math.exp(-point.y / r), phi = Math.PI / 2 - 2 * Math.atan(ts);
          for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
            con = e * Math.sin(phi);
            con = Math.pow((1 - con) / (1 + con), e / 2);
            dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
            phi += dphi;
          }
          return new LatLng(phi * d, point.x * d / r);
        }
      };
      var index = {
        __proto__: null,
        LonLat,
        Mercator,
        SphericalMercator
      };
      var EPSG3395 = extend3({}, Earth, {
        code: "EPSG:3395",
        projection: Mercator,
        transformation: (function() {
          var scale2 = 0.5 / (Math.PI * Mercator.R);
          return toTransformation(scale2, 0.5, -scale2, 0.5);
        })()
      });
      var EPSG4326 = extend3({}, Earth, {
        code: "EPSG:4326",
        projection: LonLat,
        transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
      });
      var Simple = extend3({}, CRS, {
        projection: LonLat,
        transformation: toTransformation(1, 0, -1, 0),
        scale: function(zoom2) {
          return Math.pow(2, zoom2);
        },
        zoom: function(scale2) {
          return Math.log(scale2) / Math.LN2;
        },
        distance: function(latlng1, latlng2) {
          var dx = latlng2.lng - latlng1.lng, dy = latlng2.lat - latlng1.lat;
          return Math.sqrt(dx * dx + dy * dy);
        },
        infinite: true
      });
      CRS.Earth = Earth;
      CRS.EPSG3395 = EPSG3395;
      CRS.EPSG3857 = EPSG3857;
      CRS.EPSG900913 = EPSG900913;
      CRS.EPSG4326 = EPSG4326;
      CRS.Simple = Simple;
      var Layer = Evented.extend({
        // Classes extending `L.Layer` will inherit the following options:
        options: {
          // @option pane: String = 'overlayPane'
          // By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default.
          pane: "overlayPane",
          // @option attribution: String = null
          // String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.
          attribution: null,
          bubblingMouseEvents: true
        },
        /* @section
         * Classes extending `L.Layer` will inherit the following methods:
         *
         * @method addTo(map: Map|LayerGroup): this
         * Adds the layer to the given map or layer group.
         */
        addTo: function(map4) {
          map4.addLayer(this);
          return this;
        },
        // @method remove: this
        // Removes the layer from the map it is currently active on.
        remove: function() {
          return this.removeFrom(this._map || this._mapToAdd);
        },
        // @method removeFrom(map: Map): this
        // Removes the layer from the given map
        //
        // @alternative
        // @method removeFrom(group: LayerGroup): this
        // Removes the layer from the given `LayerGroup`
        removeFrom: function(obj) {
          if (obj) {
            obj.removeLayer(this);
          }
          return this;
        },
        // @method getPane(name? : String): HTMLElement
        // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
        getPane: function(name) {
          return this._map.getPane(name ? this.options[name] || name : this.options.pane);
        },
        addInteractiveTarget: function(targetEl) {
          this._map._targets[stamp(targetEl)] = this;
          return this;
        },
        removeInteractiveTarget: function(targetEl) {
          delete this._map._targets[stamp(targetEl)];
          return this;
        },
        // @method getAttribution: String
        // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
        getAttribution: function() {
          return this.options.attribution;
        },
        _layerAdd: function(e) {
          var map4 = e.target;
          if (!map4.hasLayer(this)) {
            return;
          }
          this._map = map4;
          this._zoomAnimated = map4._zoomAnimated;
          if (this.getEvents) {
            var events = this.getEvents();
            map4.on(events, this);
            this.once("remove", function() {
              map4.off(events, this);
            }, this);
          }
          this.onAdd(map4);
          this.fire("add");
          map4.fire("layeradd", { layer: this });
        }
      });
      Map2.include({
        // @method addLayer(layer: Layer): this
        // Adds the given layer to the map
        addLayer: function(layer) {
          if (!layer._layerAdd) {
            throw new Error("The provided object is not a Layer.");
          }
          var id2 = stamp(layer);
          if (this._layers[id2]) {
            return this;
          }
          this._layers[id2] = layer;
          layer._mapToAdd = this;
          if (layer.beforeAdd) {
            layer.beforeAdd(this);
          }
          this.whenReady(layer._layerAdd, layer);
          return this;
        },
        // @method removeLayer(layer: Layer): this
        // Removes the given layer from the map.
        removeLayer: function(layer) {
          var id2 = stamp(layer);
          if (!this._layers[id2]) {
            return this;
          }
          if (this._loaded) {
            layer.onRemove(this);
          }
          delete this._layers[id2];
          if (this._loaded) {
            this.fire("layerremove", { layer });
            layer.fire("remove");
          }
          layer._map = layer._mapToAdd = null;
          return this;
        },
        // @method hasLayer(layer: Layer): Boolean
        // Returns `true` if the given layer is currently added to the map
        hasLayer: function(layer) {
          return stamp(layer) in this._layers;
        },
        /* @method eachLayer(fn: Function, context?: Object): this
         * Iterates over the layers of the map, optionally specifying context of the iterator function.
         * ```
         * map.eachLayer(function(layer){
         *     layer.bindPopup('Hello');
         * });
         * ```
         */
        eachLayer: function(method, context) {
          for (var i in this._layers) {
            method.call(context, this._layers[i]);
          }
          return this;
        },
        _addLayers: function(layers2) {
          layers2 = layers2 ? isArray(layers2) ? layers2 : [layers2] : [];
          for (var i = 0, len = layers2.length; i < len; i++) {
            this.addLayer(layers2[i]);
          }
        },
        _addZoomLimit: function(layer) {
          if (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
            this._zoomBoundLayers[stamp(layer)] = layer;
            this._updateZoomLevels();
          }
        },
        _removeZoomLimit: function(layer) {
          var id2 = stamp(layer);
          if (this._zoomBoundLayers[id2]) {
            delete this._zoomBoundLayers[id2];
            this._updateZoomLevels();
          }
        },
        _updateZoomLevels: function() {
          var minZoom = Infinity, maxZoom = -Infinity, oldZoomSpan = this._getZoomSpan();
          for (var i in this._zoomBoundLayers) {
            var options = this._zoomBoundLayers[i].options;
            minZoom = options.minZoom === void 0 ? minZoom : Math.min(minZoom, options.minZoom);
            maxZoom = options.maxZoom === void 0 ? maxZoom : Math.max(maxZoom, options.maxZoom);
          }
          this._layersMaxZoom = maxZoom === -Infinity ? void 0 : maxZoom;
          this._layersMinZoom = minZoom === Infinity ? void 0 : minZoom;
          if (oldZoomSpan !== this._getZoomSpan()) {
            this.fire("zoomlevelschange");
          }
          if (this.options.maxZoom === void 0 && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
            this.setZoom(this._layersMaxZoom);
          }
          if (this.options.minZoom === void 0 && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
            this.setZoom(this._layersMinZoom);
          }
        }
      });
      var LayerGroup = Layer.extend({
        initialize: function(layers2, options) {
          setOptions(this, options);
          this._layers = {};
          var i, len;
          if (layers2) {
            for (i = 0, len = layers2.length; i < len; i++) {
              this.addLayer(layers2[i]);
            }
          }
        },
        // @method addLayer(layer: Layer): this
        // Adds the given layer to the group.
        addLayer: function(layer) {
          var id2 = this.getLayerId(layer);
          this._layers[id2] = layer;
          if (this._map) {
            this._map.addLayer(layer);
          }
          return this;
        },
        // @method removeLayer(layer: Layer): this
        // Removes the given layer from the group.
        // @alternative
        // @method removeLayer(id: Number): this
        // Removes the layer with the given internal ID from the group.
        removeLayer: function(layer) {
          var id2 = layer in this._layers ? layer : this.getLayerId(layer);
          if (this._map && this._layers[id2]) {
            this._map.removeLayer(this._layers[id2]);
          }
          delete this._layers[id2];
          return this;
        },
        // @method hasLayer(layer: Layer): Boolean
        // Returns `true` if the given layer is currently added to the group.
        // @alternative
        // @method hasLayer(id: Number): Boolean
        // Returns `true` if the given internal ID is currently added to the group.
        hasLayer: function(layer) {
          var layerId = typeof layer === "number" ? layer : this.getLayerId(layer);
          return layerId in this._layers;
        },
        // @method clearLayers(): this
        // Removes all the layers from the group.
        clearLayers: function() {
          return this.eachLayer(this.removeLayer, this);
        },
        // @method invoke(methodName: String, …): this
        // Calls `methodName` on every layer contained in this group, passing any
        // additional parameters. Has no effect if the layers contained do not
        // implement `methodName`.
        invoke: function(methodName) {
          var args = Array.prototype.slice.call(arguments, 1), i, layer;
          for (i in this._layers) {
            layer = this._layers[i];
            if (layer[methodName]) {
              layer[methodName].apply(layer, args);
            }
          }
          return this;
        },
        onAdd: function(map4) {
          this.eachLayer(map4.addLayer, map4);
        },
        onRemove: function(map4) {
          this.eachLayer(map4.removeLayer, map4);
        },
        // @method eachLayer(fn: Function, context?: Object): this
        // Iterates over the layers of the group, optionally specifying context of the iterator function.
        // ```js
        // group.eachLayer(function (layer) {
        // 	layer.bindPopup('Hello');
        // });
        // ```
        eachLayer: function(method, context) {
          for (var i in this._layers) {
            method.call(context, this._layers[i]);
          }
          return this;
        },
        // @method getLayer(id: Number): Layer
        // Returns the layer with the given internal ID.
        getLayer: function(id2) {
          return this._layers[id2];
        },
        // @method getLayers(): Layer[]
        // Returns an array of all the layers added to the group.
        getLayers: function() {
          var layers2 = [];
          this.eachLayer(layers2.push, layers2);
          return layers2;
        },
        // @method setZIndex(zIndex: Number): this
        // Calls `setZIndex` on every layer contained in this group, passing the z-index.
        setZIndex: function(zIndex) {
          return this.invoke("setZIndex", zIndex);
        },
        // @method getLayerId(layer: Layer): Number
        // Returns the internal ID for a layer
        getLayerId: function(layer) {
          return stamp(layer);
        }
      });
      var layerGroup2 = function(layers2, options) {
        return new LayerGroup(layers2, options);
      };
      var FeatureGroup = LayerGroup.extend({
        addLayer: function(layer) {
          if (this.hasLayer(layer)) {
            return this;
          }
          layer.addEventParent(this);
          LayerGroup.prototype.addLayer.call(this, layer);
          return this.fire("layeradd", { layer });
        },
        removeLayer: function(layer) {
          if (!this.hasLayer(layer)) {
            return this;
          }
          if (layer in this._layers) {
            layer = this._layers[layer];
          }
          layer.removeEventParent(this);
          LayerGroup.prototype.removeLayer.call(this, layer);
          return this.fire("layerremove", { layer });
        },
        // @method setStyle(style: Path options): this
        // Sets the given path options to each layer of the group that has a `setStyle` method.
        setStyle: function(style2) {
          return this.invoke("setStyle", style2);
        },
        // @method bringToFront(): this
        // Brings the layer group to the top of all other layers
        bringToFront: function() {
          return this.invoke("bringToFront");
        },
        // @method bringToBack(): this
        // Brings the layer group to the back of all other layers
        bringToBack: function() {
          return this.invoke("bringToBack");
        },
        // @method getBounds(): LatLngBounds
        // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
        getBounds: function() {
          var bounds = new LatLngBounds();
          for (var id2 in this._layers) {
            var layer = this._layers[id2];
            bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
          }
          return bounds;
        }
      });
      var featureGroup = function(layers2, options) {
        return new FeatureGroup(layers2, options);
      };
      var Icon = Class2.extend({
        /* @section
         * @aka Icon options
         *
         * @option iconUrl: String = null
         * **(required)** The URL to the icon image (absolute or relative to your script path).
         *
         * @option iconRetinaUrl: String = null
         * The URL to a retina sized version of the icon image (absolute or relative to your
         * script path). Used for Retina screen devices.
         *
         * @option iconSize: Point = null
         * Size of the icon image in pixels.
         *
         * @option iconAnchor: Point = null
         * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
         * will be aligned so that this point is at the marker's geographical location. Centered
         * by default if size is specified, also can be set in CSS with negative margins.
         *
         * @option popupAnchor: Point = [0, 0]
         * The coordinates of the point from which popups will "open", relative to the icon anchor.
         *
         * @option tooltipAnchor: Point = [0, 0]
         * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
         *
         * @option shadowUrl: String = null
         * The URL to the icon shadow image. If not specified, no shadow image will be created.
         *
         * @option shadowRetinaUrl: String = null
         *
         * @option shadowSize: Point = null
         * Size of the shadow image in pixels.
         *
         * @option shadowAnchor: Point = null
         * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
         * as iconAnchor if not specified).
         *
         * @option className: String = ''
         * A custom class name to assign to both icon and shadow images. Empty by default.
         */
        options: {
          popupAnchor: [0, 0],
          tooltipAnchor: [0, 0],
          // @option crossOrigin: Boolean|String = false
          // Whether the crossOrigin attribute will be added to the tiles.
          // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
          // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
          crossOrigin: false
        },
        initialize: function(options) {
          setOptions(this, options);
        },
        // @method createIcon(oldIcon?: HTMLElement): HTMLElement
        // Called internally when the icon has to be shown, returns a `<img>` HTML element
        // styled according to the options.
        createIcon: function(oldIcon) {
          return this._createIcon("icon", oldIcon);
        },
        // @method createShadow(oldIcon?: HTMLElement): HTMLElement
        // As `createIcon`, but for the shadow beneath it.
        createShadow: function(oldIcon) {
          return this._createIcon("shadow", oldIcon);
        },
        _createIcon: function(name, oldIcon) {
          var src = this._getIconUrl(name);
          if (!src) {
            if (name === "icon") {
              throw new Error("iconUrl not set in Icon options (see the docs).");
            }
            return null;
          }
          var img = this._createImg(src, oldIcon && oldIcon.tagName === "IMG" ? oldIcon : null);
          this._setIconStyles(img, name);
          if (this.options.crossOrigin || this.options.crossOrigin === "") {
            img.crossOrigin = this.options.crossOrigin === true ? "" : this.options.crossOrigin;
          }
          return img;
        },
        _setIconStyles: function(img, name) {
          var options = this.options;
          var sizeOption = options[name + "Size"];
          if (typeof sizeOption === "number") {
            sizeOption = [sizeOption, sizeOption];
          }
          var size = toPoint(sizeOption), anchor = toPoint(name === "shadow" && options.shadowAnchor || options.iconAnchor || size && size.divideBy(2, true));
          img.className = "leaflet-marker-" + name + " " + (options.className || "");
          if (anchor) {
            img.style.marginLeft = -anchor.x + "px";
            img.style.marginTop = -anchor.y + "px";
          }
          if (size) {
            img.style.width = size.x + "px";
            img.style.height = size.y + "px";
          }
        },
        _createImg: function(src, el) {
          el = el || document.createElement("img");
          el.src = src;
          return el;
        },
        _getIconUrl: function(name) {
          return Browser.retina && this.options[name + "RetinaUrl"] || this.options[name + "Url"];
        }
      });
      function icon(options) {
        return new Icon(options);
      }
      var IconDefault = Icon.extend({
        options: {
          iconUrl: "marker-icon.png",
          iconRetinaUrl: "marker-icon-2x.png",
          shadowUrl: "marker-shadow.png",
          iconSize: [25, 41],
          iconAnchor: [12, 41],
          popupAnchor: [1, -34],
          tooltipAnchor: [16, -28],
          shadowSize: [41, 41]
        },
        _getIconUrl: function(name) {
          if (typeof IconDefault.imagePath !== "string") {
            IconDefault.imagePath = this._detectIconPath();
          }
          return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
        },
        _stripUrl: function(path2) {
          var strip = function(str, re2, idx) {
            var match2 = re2.exec(str);
            return match2 && match2[idx];
          };
          path2 = strip(path2, /^url\((['"])?(.+)\1\)$/, 2);
          return path2 && strip(path2, /^(.*)marker-icon\.png$/, 1);
        },
        _detectIconPath: function() {
          var el = create$1("div", "leaflet-default-icon-path", document.body);
          var path2 = getStyle(el, "background-image") || getStyle(el, "backgroundImage");
          document.body.removeChild(el);
          path2 = this._stripUrl(path2);
          if (path2) {
            return path2;
          }
          var link = document.querySelector('link[href$="leaflet.css"]');
          if (!link) {
            return "";
          }
          return link.href.substring(0, link.href.length - "leaflet.css".length - 1);
        }
      });
      var MarkerDrag = Handler.extend({
        initialize: function(marker3) {
          this._marker = marker3;
        },
        addHooks: function() {
          var icon2 = this._marker._icon;
          if (!this._draggable) {
            this._draggable = new Draggable(icon2, icon2, true);
          }
          this._draggable.on({
            dragstart: this._onDragStart,
            predrag: this._onPreDrag,
            drag: this._onDrag,
            dragend: this._onDragEnd
          }, this).enable();
          addClass(icon2, "leaflet-marker-draggable");
        },
        removeHooks: function() {
          this._draggable.off({
            dragstart: this._onDragStart,
            predrag: this._onPreDrag,
            drag: this._onDrag,
            dragend: this._onDragEnd
          }, this).disable();
          if (this._marker._icon) {
            removeClass(this._marker._icon, "leaflet-marker-draggable");
          }
        },
        moved: function() {
          return this._draggable && this._draggable._moved;
        },
        _adjustPan: function(e) {
          var marker3 = this._marker, map4 = marker3._map, speed = this._marker.options.autoPanSpeed, padding = this._marker.options.autoPanPadding, iconPos = getPosition(marker3._icon), bounds = map4.getPixelBounds(), origin = map4.getPixelOrigin();
          var panBounds = toBounds(
            bounds.min._subtract(origin).add(padding),
            bounds.max._subtract(origin).subtract(padding)
          );
          if (!panBounds.contains(iconPos)) {
            var movement = toPoint(
              (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) - (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
              (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) - (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
            ).multiplyBy(speed);
            map4.panBy(movement, { animate: false });
            this._draggable._newPos._add(movement);
            this._draggable._startPos._add(movement);
            setPosition(marker3._icon, this._draggable._newPos);
            this._onDrag(e);
            this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
          }
        },
        _onDragStart: function() {
          this._oldLatLng = this._marker.getLatLng();
          this._marker.closePopup && this._marker.closePopup();
          this._marker.fire("movestart").fire("dragstart");
        },
        _onPreDrag: function(e) {
          if (this._marker.options.autoPan) {
            cancelAnimFrame(this._panRequest);
            this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
          }
        },
        _onDrag: function(e) {
          var marker3 = this._marker, shadow = marker3._shadow, iconPos = getPosition(marker3._icon), latlng = marker3._map.layerPointToLatLng(iconPos);
          if (shadow) {
            setPosition(shadow, iconPos);
          }
          marker3._latlng = latlng;
          e.latlng = latlng;
          e.oldLatLng = this._oldLatLng;
          marker3.fire("move", e).fire("drag", e);
        },
        _onDragEnd: function(e) {
          cancelAnimFrame(this._panRequest);
          delete this._oldLatLng;
          this._marker.fire("moveend").fire("dragend", e);
        }
      });
      var Marker = Layer.extend({
        // @section
        // @aka Marker options
        options: {
          // @option icon: Icon = *
          // Icon instance to use for rendering the marker.
          // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
          // If not specified, a common instance of `L.Icon.Default` is used.
          icon: new IconDefault(),
          // Option inherited from "Interactive layer" abstract class
          interactive: true,
          // @option keyboard: Boolean = true
          // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
          keyboard: true,
          // @option title: String = ''
          // Text for the browser tooltip that appear on marker hover (no tooltip by default).
          // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
          title: "",
          // @option alt: String = 'Marker'
          // Text for the `alt` attribute of the icon image.
          // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
          alt: "Marker",
          // @option zIndexOffset: Number = 0
          // By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively).
          zIndexOffset: 0,
          // @option opacity: Number = 1.0
          // The opacity of the marker.
          opacity: 1,
          // @option riseOnHover: Boolean = false
          // If `true`, the marker will get on top of others when you hover the mouse over it.
          riseOnHover: false,
          // @option riseOffset: Number = 250
          // The z-index offset used for the `riseOnHover` feature.
          riseOffset: 250,
          // @option pane: String = 'markerPane'
          // `Map pane` where the markers icon will be added.
          pane: "markerPane",
          // @option shadowPane: String = 'shadowPane'
          // `Map pane` where the markers shadow will be added.
          shadowPane: "shadowPane",
          // @option bubblingMouseEvents: Boolean = false
          // When `true`, a mouse event on this marker will trigger the same event on the map
          // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
          bubblingMouseEvents: false,
          // @option autoPanOnFocus: Boolean = true
          // When `true`, the map will pan whenever the marker is focused (via
          // e.g. pressing `tab` on the keyboard) to ensure the marker is
          // visible within the map's bounds
          autoPanOnFocus: true,
          // @section Draggable marker options
          // @option draggable: Boolean = false
          // Whether the marker is draggable with mouse/touch or not.
          draggable: false,
          // @option autoPan: Boolean = false
          // Whether to pan the map when dragging this marker near its edge or not.
          autoPan: false,
          // @option autoPanPadding: Point = Point(50, 50)
          // Distance (in pixels to the left/right and to the top/bottom) of the
          // map edge to start panning the map.
          autoPanPadding: [50, 50],
          // @option autoPanSpeed: Number = 10
          // Number of pixels the map should pan by.
          autoPanSpeed: 10
        },
        /* @section
         *
         * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
         */
        initialize: function(latlng, options) {
          setOptions(this, options);
          this._latlng = toLatLng(latlng);
        },
        onAdd: function(map4) {
          this._zoomAnimated = this._zoomAnimated && map4.options.markerZoomAnimation;
          if (this._zoomAnimated) {
            map4.on("zoomanim", this._animateZoom, this);
          }
          this._initIcon();
          this.update();
        },
        onRemove: function(map4) {
          if (this.dragging && this.dragging.enabled()) {
            this.options.draggable = true;
            this.dragging.removeHooks();
          }
          delete this.dragging;
          if (this._zoomAnimated) {
            map4.off("zoomanim", this._animateZoom, this);
          }
          this._removeIcon();
          this._removeShadow();
        },
        getEvents: function() {
          return {
            zoom: this.update,
            viewreset: this.update
          };
        },
        // @method getLatLng: LatLng
        // Returns the current geographical position of the marker.
        getLatLng: function() {
          return this._latlng;
        },
        // @method setLatLng(latlng: LatLng): this
        // Changes the marker position to the given point.
        setLatLng: function(latlng) {
          var oldLatLng = this._latlng;
          this._latlng = toLatLng(latlng);
          this.update();
          return this.fire("move", { oldLatLng, latlng: this._latlng });
        },
        // @method setZIndexOffset(offset: Number): this
        // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
        setZIndexOffset: function(offset2) {
          this.options.zIndexOffset = offset2;
          return this.update();
        },
        // @method getIcon: Icon
        // Returns the current icon used by the marker
        getIcon: function() {
          return this.options.icon;
        },
        // @method setIcon(icon: Icon): this
        // Changes the marker icon.
        setIcon: function(icon2) {
          this.options.icon = icon2;
          if (this._map) {
            this._initIcon();
            this.update();
          }
          if (this._popup) {
            this.bindPopup(this._popup, this._popup.options);
          }
          return this;
        },
        getElement: function() {
          return this._icon;
        },
        update: function() {
          if (this._icon && this._map) {
            var pos = this._map.latLngToLayerPoint(this._latlng).round();
            this._setPos(pos);
          }
          return this;
        },
        _initIcon: function() {
          var options = this.options, classToAdd = "leaflet-zoom-" + (this._zoomAnimated ? "animated" : "hide");
          var icon2 = options.icon.createIcon(this._icon), addIcon = false;
          if (icon2 !== this._icon) {
            if (this._icon) {
              this._removeIcon();
            }
            addIcon = true;
            if (options.title) {
              icon2.title = options.title;
            }
            if (icon2.tagName === "IMG") {
              icon2.alt = options.alt || "";
            }
          }
          addClass(icon2, classToAdd);
          if (options.keyboard) {
            icon2.tabIndex = "0";
            icon2.setAttribute("role", "button");
          }
          this._icon = icon2;
          if (options.riseOnHover) {
            this.on({
              mouseover: this._bringToFront,
              mouseout: this._resetZIndex
            });
          }
          if (this.options.autoPanOnFocus) {
            on(icon2, "focus", this._panOnFocus, this);
          }
          var newShadow = options.icon.createShadow(this._shadow), addShadow = false;
          if (newShadow !== this._shadow) {
            this._removeShadow();
            addShadow = true;
          }
          if (newShadow) {
            addClass(newShadow, classToAdd);
            newShadow.alt = "";
          }
          this._shadow = newShadow;
          if (options.opacity < 1) {
            this._updateOpacity();
          }
          if (addIcon) {
            this.getPane().appendChild(this._icon);
          }
          this._initInteraction();
          if (newShadow && addShadow) {
            this.getPane(options.shadowPane).appendChild(this._shadow);
          }
        },
        _removeIcon: function() {
          if (this.options.riseOnHover) {
            this.off({
              mouseover: this._bringToFront,
              mouseout: this._resetZIndex
            });
          }
          if (this.options.autoPanOnFocus) {
            off(this._icon, "focus", this._panOnFocus, this);
          }
          remove2(this._icon);
          this.removeInteractiveTarget(this._icon);
          this._icon = null;
        },
        _removeShadow: function() {
          if (this._shadow) {
            remove2(this._shadow);
          }
          this._shadow = null;
        },
        _setPos: function(pos) {
          if (this._icon) {
            setPosition(this._icon, pos);
          }
          if (this._shadow) {
            setPosition(this._shadow, pos);
          }
          this._zIndex = pos.y + this.options.zIndexOffset;
          this._resetZIndex();
        },
        _updateZIndex: function(offset2) {
          if (this._icon) {
            this._icon.style.zIndex = this._zIndex + offset2;
          }
        },
        _animateZoom: function(opt) {
          var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
          this._setPos(pos);
        },
        _initInteraction: function() {
          if (!this.options.interactive) {
            return;
          }
          addClass(this._icon, "leaflet-interactive");
          this.addInteractiveTarget(this._icon);
          if (MarkerDrag) {
            var draggable = this.options.draggable;
            if (this.dragging) {
              draggable = this.dragging.enabled();
              this.dragging.disable();
            }
            this.dragging = new MarkerDrag(this);
            if (draggable) {
              this.dragging.enable();
            }
          }
        },
        // @method setOpacity(opacity: Number): this
        // Changes the opacity of the marker.
        setOpacity: function(opacity) {
          this.options.opacity = opacity;
          if (this._map) {
            this._updateOpacity();
          }
          return this;
        },
        _updateOpacity: function() {
          var opacity = this.options.opacity;
          if (this._icon) {
            setOpacity(this._icon, opacity);
          }
          if (this._shadow) {
            setOpacity(this._shadow, opacity);
          }
        },
        _bringToFront: function() {
          this._updateZIndex(this.options.riseOffset);
        },
        _resetZIndex: function() {
          this._updateZIndex(0);
        },
        _panOnFocus: function() {
          var map4 = this._map;
          if (!map4) {
            return;
          }
          var iconOpts = this.options.icon.options;
          var size = iconOpts.iconSize ? toPoint(iconOpts.iconSize) : toPoint(0, 0);
          var anchor = iconOpts.iconAnchor ? toPoint(iconOpts.iconAnchor) : toPoint(0, 0);
          map4.panInside(this._latlng, {
            paddingTopLeft: anchor,
            paddingBottomRight: size.subtract(anchor)
          });
        },
        _getPopupAnchor: function() {
          return this.options.icon.options.popupAnchor;
        },
        _getTooltipAnchor: function() {
          return this.options.icon.options.tooltipAnchor;
        }
      });
      function marker2(latlng, options) {
        return new Marker(latlng, options);
      }
      var Path2 = Layer.extend({
        // @section
        // @aka Path options
        options: {
          // @option stroke: Boolean = true
          // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
          stroke: true,
          // @option color: String = '#3388ff'
          // Stroke color
          color: "#3388ff",
          // @option weight: Number = 3
          // Stroke width in pixels
          weight: 3,
          // @option opacity: Number = 1.0
          // Stroke opacity
          opacity: 1,
          // @option lineCap: String= 'round'
          // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
          lineCap: "round",
          // @option lineJoin: String = 'round'
          // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
          lineJoin: "round",
          // @option dashArray: String = null
          // A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
          dashArray: null,
          // @option dashOffset: String = null
          // A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
          dashOffset: null,
          // @option fill: Boolean = depends
          // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
          fill: false,
          // @option fillColor: String = *
          // Fill color. Defaults to the value of the [`color`](#path-color) option
          fillColor: null,
          // @option fillOpacity: Number = 0.2
          // Fill opacity.
          fillOpacity: 0.2,
          // @option fillRule: String = 'evenodd'
          // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
          fillRule: "evenodd",
          // className: '',
          // Option inherited from "Interactive layer" abstract class
          interactive: true,
          // @option bubblingMouseEvents: Boolean = true
          // When `true`, a mouse event on this path will trigger the same event on the map
          // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
          bubblingMouseEvents: true
        },
        beforeAdd: function(map4) {
          this._renderer = map4.getRenderer(this);
        },
        onAdd: function() {
          this._renderer._initPath(this);
          this._reset();
          this._renderer._addPath(this);
        },
        onRemove: function() {
          this._renderer._removePath(this);
        },
        // @method redraw(): this
        // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
        redraw: function() {
          if (this._map) {
            this._renderer._updatePath(this);
          }
          return this;
        },
        // @method setStyle(style: Path options): this
        // Changes the appearance of a Path based on the options in the `Path options` object.
        setStyle: function(style2) {
          setOptions(this, style2);
          if (this._renderer) {
            this._renderer._updateStyle(this);
            if (this.options.stroke && style2 && Object.prototype.hasOwnProperty.call(style2, "weight")) {
              this._updateBounds();
            }
          }
          return this;
        },
        // @method bringToFront(): this
        // Brings the layer to the top of all path layers.
        bringToFront: function() {
          if (this._renderer) {
            this._renderer._bringToFront(this);
          }
          return this;
        },
        // @method bringToBack(): this
        // Brings the layer to the bottom of all path layers.
        bringToBack: function() {
          if (this._renderer) {
            this._renderer._bringToBack(this);
          }
          return this;
        },
        getElement: function() {
          return this._path;
        },
        _reset: function() {
          this._project();
          this._update();
        },
        _clickTolerance: function() {
          return (this.options.stroke ? this.options.weight / 2 : 0) + (this._renderer.options.tolerance || 0);
        }
      });
      var CircleMarker = Path2.extend({
        // @section
        // @aka CircleMarker options
        options: {
          fill: true,
          // @option radius: Number = 10
          // Radius of the circle marker, in pixels
          radius: 10
        },
        initialize: function(latlng, options) {
          setOptions(this, options);
          this._latlng = toLatLng(latlng);
          this._radius = this.options.radius;
        },
        // @method setLatLng(latLng: LatLng): this
        // Sets the position of a circle marker to a new location.
        setLatLng: function(latlng) {
          var oldLatLng = this._latlng;
          this._latlng = toLatLng(latlng);
          this.redraw();
          return this.fire("move", { oldLatLng, latlng: this._latlng });
        },
        // @method getLatLng(): LatLng
        // Returns the current geographical position of the circle marker
        getLatLng: function() {
          return this._latlng;
        },
        // @method setRadius(radius: Number): this
        // Sets the radius of a circle marker. Units are in pixels.
        setRadius: function(radius) {
          this.options.radius = this._radius = radius;
          return this.redraw();
        },
        // @method getRadius(): Number
        // Returns the current radius of the circle
        getRadius: function() {
          return this._radius;
        },
        setStyle: function(options) {
          var radius = options && options.radius || this._radius;
          Path2.prototype.setStyle.call(this, options);
          this.setRadius(radius);
          return this;
        },
        _project: function() {
          this._point = this._map.latLngToLayerPoint(this._latlng);
          this._updateBounds();
        },
        _updateBounds: function() {
          var r = this._radius, r2 = this._radiusY || r, w = this._clickTolerance(), p = [r + w, r2 + w];
          this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
        },
        _update: function() {
          if (this._map) {
            this._updatePath();
          }
        },
        _updatePath: function() {
          this._renderer._updateCircle(this);
        },
        _empty: function() {
          return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
        },
        // Needed by the `Canvas` renderer for interactivity
        _containsPoint: function(p) {
          return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
        }
      });
      function circleMarker(latlng, options) {
        return new CircleMarker(latlng, options);
      }
      var Circle = CircleMarker.extend({
        initialize: function(latlng, options, legacyOptions) {
          if (typeof options === "number") {
            options = extend3({}, legacyOptions, { radius: options });
          }
          setOptions(this, options);
          this._latlng = toLatLng(latlng);
          if (isNaN(this.options.radius)) {
            throw new Error("Circle radius cannot be NaN");
          }
          this._mRadius = this.options.radius;
        },
        // @method setRadius(radius: Number): this
        // Sets the radius of a circle. Units are in meters.
        setRadius: function(radius) {
          this._mRadius = radius;
          return this.redraw();
        },
        // @method getRadius(): Number
        // Returns the current radius of a circle. Units are in meters.
        getRadius: function() {
          return this._mRadius;
        },
        // @method getBounds(): LatLngBounds
        // Returns the `LatLngBounds` of the path.
        getBounds: function() {
          var half = [this._radius, this._radiusY || this._radius];
          return new LatLngBounds(
            this._map.layerPointToLatLng(this._point.subtract(half)),
            this._map.layerPointToLatLng(this._point.add(half))
          );
        },
        setStyle: Path2.prototype.setStyle,
        _project: function() {
          var lng = this._latlng.lng, lat = this._latlng.lat, map4 = this._map, crs = map4.options.crs;
          if (crs.distance === Earth.distance) {
            var d = Math.PI / 180, latR = this._mRadius / Earth.R / d, top2 = map4.project([lat + latR, lng]), bottom2 = map4.project([lat - latR, lng]), p = top2.add(bottom2).divideBy(2), lat2 = map4.unproject(p).lat, lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) / (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
            if (isNaN(lngR) || lngR === 0) {
              lngR = latR / Math.cos(Math.PI / 180 * lat);
            }
            this._point = p.subtract(map4.getPixelOrigin());
            this._radius = isNaN(lngR) ? 0 : p.x - map4.project([lat2, lng - lngR]).x;
            this._radiusY = p.y - top2.y;
          } else {
            var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
            this._point = map4.latLngToLayerPoint(this._latlng);
            this._radius = this._point.x - map4.latLngToLayerPoint(latlng2).x;
          }
          this._updateBounds();
        }
      });
      function circle2(latlng, options, legacyOptions) {
        return new Circle(latlng, options, legacyOptions);
      }
      var Polyline = Path2.extend({
        // @section
        // @aka Polyline options
        options: {
          // @option smoothFactor: Number = 1.0
          // How much to simplify the polyline on each zoom level. More means
          // better performance and smoother look, and less means more accurate representation.
          smoothFactor: 1,
          // @option noClip: Boolean = false
          // Disable polyline clipping.
          noClip: false
        },
        initialize: function(latlngs, options) {
          setOptions(this, options);
          this._setLatLngs(latlngs);
        },
        // @method getLatLngs(): LatLng[]
        // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
        getLatLngs: function() {
          return this._latlngs;
        },
        // @method setLatLngs(latlngs: LatLng[]): this
        // Replaces all the points in the polyline with the given array of geographical points.
        setLatLngs: function(latlngs) {
          this._setLatLngs(latlngs);
          return this.redraw();
        },
        // @method isEmpty(): Boolean
        // Returns `true` if the Polyline has no LatLngs.
        isEmpty: function() {
          return !this._latlngs.length;
        },
        // @method closestLayerPoint(p: Point): Point
        // Returns the point closest to `p` on the Polyline.
        closestLayerPoint: function(p) {
          var minDistance = Infinity, minPoint = null, closest = _sqClosestPointOnSegment, p1, p2;
          for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
            var points = this._parts[j];
            for (var i = 1, len = points.length; i < len; i++) {
              p1 = points[i - 1];
              p2 = points[i];
              var sqDist = closest(p, p1, p2, true);
              if (sqDist < minDistance) {
                minDistance = sqDist;
                minPoint = closest(p, p1, p2);
              }
            }
          }
          if (minPoint) {
            minPoint.distance = Math.sqrt(minDistance);
          }
          return minPoint;
        },
        // @method getCenter(): LatLng
        // Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline.
        getCenter: function() {
          if (!this._map) {
            throw new Error("Must add layer to map before using getCenter()");
          }
          return polylineCenter(this._defaultShape(), this._map.options.crs);
        },
        // @method getBounds(): LatLngBounds
        // Returns the `LatLngBounds` of the path.
        getBounds: function() {
          return this._bounds;
        },
        // @method addLatLng(latlng: LatLng, latlngs?: LatLng[]): this
        // Adds a given point to the polyline. By default, adds to the first ring of
        // the polyline in case of a multi-polyline, but can be overridden by passing
        // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
        addLatLng: function(latlng, latlngs) {
          latlngs = latlngs || this._defaultShape();
          latlng = toLatLng(latlng);
          latlngs.push(latlng);
          this._bounds.extend(latlng);
          return this.redraw();
        },
        _setLatLngs: function(latlngs) {
          this._bounds = new LatLngBounds();
          this._latlngs = this._convertLatLngs(latlngs);
        },
        _defaultShape: function() {
          return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
        },
        // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
        _convertLatLngs: function(latlngs) {
          var result = [], flat = isFlat(latlngs);
          for (var i = 0, len = latlngs.length; i < len; i++) {
            if (flat) {
              result[i] = toLatLng(latlngs[i]);
              this._bounds.extend(result[i]);
            } else {
              result[i] = this._convertLatLngs(latlngs[i]);
            }
          }
          return result;
        },
        _project: function() {
          var pxBounds = new Bounds();
          this._rings = [];
          this._projectLatlngs(this._latlngs, this._rings, pxBounds);
          if (this._bounds.isValid() && pxBounds.isValid()) {
            this._rawPxBounds = pxBounds;
            this._updateBounds();
          }
        },
        _updateBounds: function() {
          var w = this._clickTolerance(), p = new Point(w, w);
          if (!this._rawPxBounds) {
            return;
          }
          this._pxBounds = new Bounds([
            this._rawPxBounds.min.subtract(p),
            this._rawPxBounds.max.add(p)
          ]);
        },
        // recursively turns latlngs into a set of rings with projected coordinates
        _projectLatlngs: function(latlngs, result, projectedBounds) {
          var flat = latlngs[0] instanceof LatLng, len = latlngs.length, i, ring;
          if (flat) {
            ring = [];
            for (i = 0; i < len; i++) {
              ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
              projectedBounds.extend(ring[i]);
            }
            result.push(ring);
          } else {
            for (i = 0; i < len; i++) {
              this._projectLatlngs(latlngs[i], result, projectedBounds);
            }
          }
        },
        // clip polyline by renderer bounds so that we have less to render for performance
        _clipPoints: function() {
          var bounds = this._renderer._bounds;
          this._parts = [];
          if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
            return;
          }
          if (this.options.noClip) {
            this._parts = this._rings;
            return;
          }
          var parts = this._parts, i, j, k, len, len2, segment, points;
          for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
            points = this._rings[i];
            for (j = 0, len2 = points.length; j < len2 - 1; j++) {
              segment = clipSegment(points[j], points[j + 1], bounds, j, true);
              if (!segment) {
                continue;
              }
              parts[k] = parts[k] || [];
              parts[k].push(segment[0]);
              if (segment[1] !== points[j + 1] || j === len2 - 2) {
                parts[k].push(segment[1]);
                k++;
              }
            }
          }
        },
        // simplify each clipped part of the polyline for performance
        _simplifyPoints: function() {
          var parts = this._parts, tolerance = this.options.smoothFactor;
          for (var i = 0, len = parts.length; i < len; i++) {
            parts[i] = simplify(parts[i], tolerance);
          }
        },
        _update: function() {
          if (!this._map) {
            return;
          }
          this._clipPoints();
          this._simplifyPoints();
          this._updatePath();
        },
        _updatePath: function() {
          this._renderer._updatePoly(this);
        },
        // Needed by the `Canvas` renderer for interactivity
        _containsPoint: function(p, closed) {
          var i, j, k, len, len2, part, w = this._clickTolerance();
          if (!this._pxBounds || !this._pxBounds.contains(p)) {
            return false;
          }
          for (i = 0, len = this._parts.length; i < len; i++) {
            part = this._parts[i];
            for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
              if (!closed && j === 0) {
                continue;
              }
              if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
                return true;
              }
            }
          }
          return false;
        }
      });
      function polyline(latlngs, options) {
        return new Polyline(latlngs, options);
      }
      Polyline._flat = _flat;
      var Polygon = Polyline.extend({
        options: {
          fill: true
        },
        isEmpty: function() {
          return !this._latlngs.length || !this._latlngs[0].length;
        },
        // @method getCenter(): LatLng
        // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the Polygon.
        getCenter: function() {
          if (!this._map) {
            throw new Error("Must add layer to map before using getCenter()");
          }
          return polygonCenter(this._defaultShape(), this._map.options.crs);
        },
        _convertLatLngs: function(latlngs) {
          var result = Polyline.prototype._convertLatLngs.call(this, latlngs), len = result.length;
          if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
            result.pop();
          }
          return result;
        },
        _setLatLngs: function(latlngs) {
          Polyline.prototype._setLatLngs.call(this, latlngs);
          if (isFlat(this._latlngs)) {
            this._latlngs = [this._latlngs];
          }
        },
        _defaultShape: function() {
          return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
        },
        _clipPoints: function() {
          var bounds = this._renderer._bounds, w = this.options.weight, p = new Point(w, w);
          bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
          this._parts = [];
          if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
            return;
          }
          if (this.options.noClip) {
            this._parts = this._rings;
            return;
          }
          for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
            clipped = clipPolygon(this._rings[i], bounds, true);
            if (clipped.length) {
              this._parts.push(clipped);
            }
          }
        },
        _updatePath: function() {
          this._renderer._updatePoly(this, true);
        },
        // Needed by the `Canvas` renderer for interactivity
        _containsPoint: function(p) {
          var inside = false, part, p1, p2, i, j, k, len, len2;
          if (!this._pxBounds || !this._pxBounds.contains(p)) {
            return false;
          }
          for (i = 0, len = this._parts.length; i < len; i++) {
            part = this._parts[i];
            for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
              p1 = part[j];
              p2 = part[k];
              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) {
                inside = !inside;
              }
            }
          }
          return inside || Polyline.prototype._containsPoint.call(this, p, true);
        }
      });
      function polygon(latlngs, options) {
        return new Polygon(latlngs, options);
      }
      var GeoJSON = FeatureGroup.extend({
        /* @section
         * @aka GeoJSON options
         *
         * @option pointToLayer: Function = *
         * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
         * called when data is added, passing the GeoJSON point feature and its `LatLng`.
         * The default is to spawn a default `Marker`:
         * ```js
         * function(geoJsonPoint, latlng) {
         * 	return L.marker(latlng);
         * }
         * ```
         *
         * @option style: Function = *
         * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
         * called internally when data is added.
         * The default value is to not override any defaults:
         * ```js
         * function (geoJsonFeature) {
         * 	return {}
         * }
         * ```
         *
         * @option onEachFeature: Function = *
         * A `Function` that will be called once for each created `Feature`, after it has
         * been created and styled. Useful for attaching events and popups to features.
         * The default is to do nothing with the newly created layers:
         * ```js
         * function (feature, layer) {}
         * ```
         *
         * @option filter: Function = *
         * A `Function` that will be used to decide whether to include a feature or not.
         * The default is to include all features:
         * ```js
         * function (geoJsonFeature) {
         * 	return true;
         * }
         * ```
         * Note: dynamically changing the `filter` option will have effect only on newly
         * added data. It will _not_ re-evaluate already included features.
         *
         * @option coordsToLatLng: Function = *
         * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
         * The default is the `coordsToLatLng` static method.
         *
         * @option markersInheritOptions: Boolean = false
         * Whether default Markers for "Point" type Features inherit from group options.
         */
        initialize: function(geojson, options) {
          setOptions(this, options);
          this._layers = {};
          if (geojson) {
            this.addData(geojson);
          }
        },
        // @method addData( <GeoJSON> data ): this
        // Adds a GeoJSON object to the layer.
        addData: function(geojson) {
          var features = isArray(geojson) ? geojson : geojson.features, i, len, feature;
          if (features) {
            for (i = 0, len = features.length; i < len; i++) {
              feature = features[i];
              if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
                this.addData(feature);
              }
            }
            return this;
          }
          var options = this.options;
          if (options.filter && !options.filter(geojson)) {
            return this;
          }
          var layer = geometryToLayer(geojson, options);
          if (!layer) {
            return this;
          }
          layer.feature = asFeature(geojson);
          layer.defaultOptions = layer.options;
          this.resetStyle(layer);
          if (options.onEachFeature) {
            options.onEachFeature(geojson, layer);
          }
          return this.addLayer(layer);
        },
        // @method resetStyle( <Path> layer? ): this
        // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
        // If `layer` is omitted, the style of all features in the current layer is reset.
        resetStyle: function(layer) {
          if (layer === void 0) {
            return this.eachLayer(this.resetStyle, this);
          }
          layer.options = extend3({}, layer.defaultOptions);
          this._setLayerStyle(layer, this.options.style);
          return this;
        },
        // @method setStyle( <Function> style ): this
        // Changes styles of GeoJSON vector layers with the given style function.
        setStyle: function(style2) {
          return this.eachLayer(function(layer) {
            this._setLayerStyle(layer, style2);
          }, this);
        },
        _setLayerStyle: function(layer, style2) {
          if (layer.setStyle) {
            if (typeof style2 === "function") {
              style2 = style2(layer.feature);
            }
            layer.setStyle(style2);
          }
        }
      });
      function geometryToLayer(geojson, options) {
        var geometry = geojson.type === "Feature" ? geojson.geometry : geojson, coords = geometry ? geometry.coordinates : null, layers2 = [], pointToLayer = options && options.pointToLayer, _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng, latlng, latlngs, i, len;
        if (!coords && !geometry) {
          return null;
        }
        switch (geometry.type) {
          case "Point":
            latlng = _coordsToLatLng(coords);
            return _pointToLayer(pointToLayer, geojson, latlng, options);
          case "MultiPoint":
            for (i = 0, len = coords.length; i < len; i++) {
              latlng = _coordsToLatLng(coords[i]);
              layers2.push(_pointToLayer(pointToLayer, geojson, latlng, options));
            }
            return new FeatureGroup(layers2);
          case "LineString":
          case "MultiLineString":
            latlngs = coordsToLatLngs(coords, geometry.type === "LineString" ? 0 : 1, _coordsToLatLng);
            return new Polyline(latlngs, options);
          case "Polygon":
          case "MultiPolygon":
            latlngs = coordsToLatLngs(coords, geometry.type === "Polygon" ? 1 : 2, _coordsToLatLng);
            return new Polygon(latlngs, options);
          case "GeometryCollection":
            for (i = 0, len = geometry.geometries.length; i < len; i++) {
              var geoLayer = geometryToLayer({
                geometry: geometry.geometries[i],
                type: "Feature",
                properties: geojson.properties
              }, options);
              if (geoLayer) {
                layers2.push(geoLayer);
              }
            }
            return new FeatureGroup(layers2);
          case "FeatureCollection":
            for (i = 0, len = geometry.features.length; i < len; i++) {
              var featureLayer = geometryToLayer(geometry.features[i], options);
              if (featureLayer) {
                layers2.push(featureLayer);
              }
            }
            return new FeatureGroup(layers2);
          default:
            throw new Error("Invalid GeoJSON object.");
        }
      }
      function _pointToLayer(pointToLayerFn, geojson, latlng, options) {
        return pointToLayerFn ? pointToLayerFn(geojson, latlng) : new Marker(latlng, options && options.markersInheritOptions && options);
      }
      function coordsToLatLng(coords) {
        return new LatLng(coords[1], coords[0], coords[2]);
      }
      function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
        var latlngs = [];
        for (var i = 0, len = coords.length, latlng; i < len; i++) {
          latlng = levelsDeep ? coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) : (_coordsToLatLng || coordsToLatLng)(coords[i]);
          latlngs.push(latlng);
        }
        return latlngs;
      }
      function latLngToCoords(latlng, precision) {
        latlng = toLatLng(latlng);
        return latlng.alt !== void 0 ? [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] : [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
      }
      function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
        var coords = [];
        for (var i = 0, len = latlngs.length; i < len; i++) {
          coords.push(levelsDeep ? latLngsToCoords(latlngs[i], isFlat(latlngs[i]) ? 0 : levelsDeep - 1, closed, precision) : latLngToCoords(latlngs[i], precision));
        }
        if (!levelsDeep && closed && coords.length > 0) {
          coords.push(coords[0].slice());
        }
        return coords;
      }
      function getFeature(layer, newGeometry) {
        return layer.feature ? extend3({}, layer.feature, { geometry: newGeometry }) : asFeature(newGeometry);
      }
      function asFeature(geojson) {
        if (geojson.type === "Feature" || geojson.type === "FeatureCollection") {
          return geojson;
        }
        return {
          type: "Feature",
          properties: {},
          geometry: geojson
        };
      }
      var PointToGeoJSON = {
        toGeoJSON: function(precision) {
          return getFeature(this, {
            type: "Point",
            coordinates: latLngToCoords(this.getLatLng(), precision)
          });
        }
      };
      Marker.include(PointToGeoJSON);
      Circle.include(PointToGeoJSON);
      CircleMarker.include(PointToGeoJSON);
      Polyline.include({
        toGeoJSON: function(precision) {
          var multi = !isFlat(this._latlngs);
          var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
          return getFeature(this, {
            type: (multi ? "Multi" : "") + "LineString",
            coordinates: coords
          });
        }
      });
      Polygon.include({
        toGeoJSON: function(precision) {
          var holes = !isFlat(this._latlngs), multi = holes && !isFlat(this._latlngs[0]);
          var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
          if (!holes) {
            coords = [coords];
          }
          return getFeature(this, {
            type: (multi ? "Multi" : "") + "Polygon",
            coordinates: coords
          });
        }
      });
      LayerGroup.include({
        toMultiPoint: function(precision) {
          var coords = [];
          this.eachLayer(function(layer) {
            coords.push(layer.toGeoJSON(precision).geometry.coordinates);
          });
          return getFeature(this, {
            type: "MultiPoint",
            coordinates: coords
          });
        },
        // @method toGeoJSON(precision?: Number|false): Object
        // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
        // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
        toGeoJSON: function(precision) {
          var type = this.feature && this.feature.geometry && this.feature.geometry.type;
          if (type === "MultiPoint") {
            return this.toMultiPoint(precision);
          }
          var isGeometryCollection = type === "GeometryCollection", jsons = [];
          this.eachLayer(function(layer) {
            if (layer.toGeoJSON) {
              var json2 = layer.toGeoJSON(precision);
              if (isGeometryCollection) {
                jsons.push(json2.geometry);
              } else {
                var feature = asFeature(json2);
                if (feature.type === "FeatureCollection") {
                  jsons.push.apply(jsons, feature.features);
                } else {
                  jsons.push(feature);
                }
              }
            }
          });
          if (isGeometryCollection) {
            return getFeature(this, {
              geometries: jsons,
              type: "GeometryCollection"
            });
          }
          return {
            type: "FeatureCollection",
            features: jsons
          };
        }
      });
      function geoJSON(geojson, options) {
        return new GeoJSON(geojson, options);
      }
      var geoJson = geoJSON;
      var ImageOverlay = Layer.extend({
        // @section
        // @aka ImageOverlay options
        options: {
          // @option opacity: Number = 1.0
          // The opacity of the image overlay.
          opacity: 1,
          // @option alt: String = ''
          // Text for the `alt` attribute of the image (useful for accessibility).
          alt: "",
          // @option interactive: Boolean = false
          // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
          interactive: false,
          // @option crossOrigin: Boolean|String = false
          // Whether the crossOrigin attribute will be added to the image.
          // If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data.
          // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
          crossOrigin: false,
          // @option errorOverlayUrl: String = ''
          // URL to the overlay image to show in place of the overlay that failed to load.
          errorOverlayUrl: "",
          // @option zIndex: Number = 1
          // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
          zIndex: 1,
          // @option className: String = ''
          // A custom class name to assign to the image. Empty by default.
          className: ""
        },
        initialize: function(url2, bounds, options) {
          this._url = url2;
          this._bounds = toLatLngBounds(bounds);
          setOptions(this, options);
        },
        onAdd: function() {
          if (!this._image) {
            this._initImage();
            if (this.options.opacity < 1) {
              this._updateOpacity();
            }
          }
          if (this.options.interactive) {
            addClass(this._image, "leaflet-interactive");
            this.addInteractiveTarget(this._image);
          }
          this.getPane().appendChild(this._image);
          this._reset();
        },
        onRemove: function() {
          remove2(this._image);
          if (this.options.interactive) {
            this.removeInteractiveTarget(this._image);
          }
        },
        // @method setOpacity(opacity: Number): this
        // Sets the opacity of the overlay.
        setOpacity: function(opacity) {
          this.options.opacity = opacity;
          if (this._image) {
            this._updateOpacity();
          }
          return this;
        },
        setStyle: function(styleOpts) {
          if (styleOpts.opacity) {
            this.setOpacity(styleOpts.opacity);
          }
          return this;
        },
        // @method bringToFront(): this
        // Brings the layer to the top of all overlays.
        bringToFront: function() {
          if (this._map) {
            toFront(this._image);
          }
          return this;
        },
        // @method bringToBack(): this
        // Brings the layer to the bottom of all overlays.
        bringToBack: function() {
          if (this._map) {
            toBack(this._image);
          }
          return this;
        },
        // @method setUrl(url: String): this
        // Changes the URL of the image.
        setUrl: function(url2) {
          this._url = url2;
          if (this._image) {
            this._image.src = url2;
          }
          return this;
        },
        // @method setBounds(bounds: LatLngBounds): this
        // Update the bounds that this ImageOverlay covers
        setBounds: function(bounds) {
          this._bounds = toLatLngBounds(bounds);
          if (this._map) {
            this._reset();
          }
          return this;
        },
        getEvents: function() {
          var events = {
            zoom: this._reset,
            viewreset: this._reset
          };
          if (this._zoomAnimated) {
            events.zoomanim = this._animateZoom;
          }
          return events;
        },
        // @method setZIndex(value: Number): this
        // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
        setZIndex: function(value) {
          this.options.zIndex = value;
          this._updateZIndex();
          return this;
        },
        // @method getBounds(): LatLngBounds
        // Get the bounds that this ImageOverlay covers
        getBounds: function() {
          return this._bounds;
        },
        // @method getElement(): HTMLElement
        // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
        // used by this overlay.
        getElement: function() {
          return this._image;
        },
        _initImage: function() {
          var wasElementSupplied = this._url.tagName === "IMG";
          var img = this._image = wasElementSupplied ? this._url : create$1("img");
          addClass(img, "leaflet-image-layer");
          if (this._zoomAnimated) {
            addClass(img, "leaflet-zoom-animated");
          }
          if (this.options.className) {
            addClass(img, this.options.className);
          }
          img.onselectstart = falseFn;
          img.onmousemove = falseFn;
          img.onload = bind(this.fire, this, "load");
          img.onerror = bind(this._overlayOnError, this, "error");
          if (this.options.crossOrigin || this.options.crossOrigin === "") {
            img.crossOrigin = this.options.crossOrigin === true ? "" : this.options.crossOrigin;
          }
          if (this.options.zIndex) {
            this._updateZIndex();
          }
          if (wasElementSupplied) {
            this._url = img.src;
            return;
          }
          img.src = this._url;
          img.alt = this.options.alt;
        },
        _animateZoom: function(e) {
          var scale2 = this._map.getZoomScale(e.zoom), offset2 = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
          setTransform(this._image, offset2, scale2);
        },
        _reset: function() {
          var image = this._image, bounds = new Bounds(
            this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
            this._map.latLngToLayerPoint(this._bounds.getSouthEast())
          ), size = bounds.getSize();
          setPosition(image, bounds.min);
          image.style.width = size.x + "px";
          image.style.height = size.y + "px";
        },
        _updateOpacity: function() {
          setOpacity(this._image, this.options.opacity);
        },
        _updateZIndex: function() {
          if (this._image && this.options.zIndex !== void 0 && this.options.zIndex !== null) {
            this._image.style.zIndex = this.options.zIndex;
          }
        },
        _overlayOnError: function() {
          this.fire("error");
          var errorUrl = this.options.errorOverlayUrl;
          if (errorUrl && this._url !== errorUrl) {
            this._url = errorUrl;
            this._image.src = errorUrl;
          }
        },
        // @method getCenter(): LatLng
        // Returns the center of the ImageOverlay.
        getCenter: function() {
          return this._bounds.getCenter();
        }
      });
      var imageOverlay = function(url2, bounds, options) {
        return new ImageOverlay(url2, bounds, options);
      };
      var VideoOverlay = ImageOverlay.extend({
        // @section
        // @aka VideoOverlay options
        options: {
          // @option autoplay: Boolean = true
          // Whether the video starts playing automatically when loaded.
          // On some browsers autoplay will only work with `muted: true`
          autoplay: true,
          // @option loop: Boolean = true
          // Whether the video will loop back to the beginning when played.
          loop: true,
          // @option keepAspectRatio: Boolean = true
          // Whether the video will save aspect ratio after the projection.
          // Relevant for supported browsers. See [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
          keepAspectRatio: true,
          // @option muted: Boolean = false
          // Whether the video starts on mute when loaded.
          muted: false,
          // @option playsInline: Boolean = true
          // Mobile browsers will play the video right where it is instead of open it up in fullscreen mode.
          playsInline: true
        },
        _initImage: function() {
          var wasElementSupplied = this._url.tagName === "VIDEO";
          var vid = this._image = wasElementSupplied ? this._url : create$1("video");
          addClass(vid, "leaflet-image-layer");
          if (this._zoomAnimated) {
            addClass(vid, "leaflet-zoom-animated");
          }
          if (this.options.className) {
            addClass(vid, this.options.className);
          }
          vid.onselectstart = falseFn;
          vid.onmousemove = falseFn;
          vid.onloadeddata = bind(this.fire, this, "load");
          if (wasElementSupplied) {
            var sourceElements = vid.getElementsByTagName("source");
            var sources = [];
            for (var j = 0; j < sourceElements.length; j++) {
              sources.push(sourceElements[j].src);
            }
            this._url = sourceElements.length > 0 ? sources : [vid.src];
            return;
          }
          if (!isArray(this._url)) {
            this._url = [this._url];
          }
          if (!this.options.keepAspectRatio && Object.prototype.hasOwnProperty.call(vid.style, "objectFit")) {
            vid.style["objectFit"] = "fill";
          }
          vid.autoplay = !!this.options.autoplay;
          vid.loop = !!this.options.loop;
          vid.muted = !!this.options.muted;
          vid.playsInline = !!this.options.playsInline;
          for (var i = 0; i < this._url.length; i++) {
            var source = create$1("source");
            source.src = this._url[i];
            vid.appendChild(source);
          }
        }
        // @method getElement(): HTMLVideoElement
        // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
        // used by this overlay.
      });
      function videoOverlay(video, bounds, options) {
        return new VideoOverlay(video, bounds, options);
      }
      var SVGOverlay = ImageOverlay.extend({
        _initImage: function() {
          var el = this._image = this._url;
          addClass(el, "leaflet-image-layer");
          if (this._zoomAnimated) {
            addClass(el, "leaflet-zoom-animated");
          }
          if (this.options.className) {
            addClass(el, this.options.className);
          }
          el.onselectstart = falseFn;
          el.onmousemove = falseFn;
        }
        // @method getElement(): SVGElement
        // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
        // used by this overlay.
      });
      function svgOverlay(el, bounds, options) {
        return new SVGOverlay(el, bounds, options);
      }
      var DivOverlay = Layer.extend({
        // @section
        // @aka DivOverlay options
        options: {
          // @option interactive: Boolean = false
          // If true, the popup/tooltip will listen to the mouse events.
          interactive: false,
          // @option offset: Point = Point(0, 0)
          // The offset of the overlay position.
          offset: [0, 0],
          // @option className: String = ''
          // A custom CSS class name to assign to the overlay.
          className: "",
          // @option pane: String = undefined
          // `Map pane` where the overlay will be added.
          pane: void 0,
          // @option content: String|HTMLElement|Function = ''
          // Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be
          // passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay.
          content: ""
        },
        initialize: function(options, source) {
          if (options && (options instanceof LatLng || isArray(options))) {
            this._latlng = toLatLng(options);
            setOptions(this, source);
          } else {
            setOptions(this, options);
            this._source = source;
          }
          if (this.options.content) {
            this._content = this.options.content;
          }
        },
        // @method openOn(map: Map): this
        // Adds the overlay to the map.
        // Alternative to `map.openPopup(popup)`/`.openTooltip(tooltip)`.
        openOn: function(map4) {
          map4 = arguments.length ? map4 : this._source._map;
          if (!map4.hasLayer(this)) {
            map4.addLayer(this);
          }
          return this;
        },
        // @method close(): this
        // Closes the overlay.
        // Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)`
        // and `layer.closePopup()`/`.closeTooltip()`.
        close: function() {
          if (this._map) {
            this._map.removeLayer(this);
          }
          return this;
        },
        // @method toggle(layer?: Layer): this
        // Opens or closes the overlay bound to layer depending on its current state.
        // Argument may be omitted only for overlay bound to layer.
        // Alternative to `layer.togglePopup()`/`.toggleTooltip()`.
        toggle: function(layer) {
          if (this._map) {
            this.close();
          } else {
            if (arguments.length) {
              this._source = layer;
            } else {
              layer = this._source;
            }
            this._prepareOpen();
            this.openOn(layer._map);
          }
          return this;
        },
        onAdd: function(map4) {
          this._zoomAnimated = map4._zoomAnimated;
          if (!this._container) {
            this._initLayout();
          }
          if (map4._fadeAnimated) {
            setOpacity(this._container, 0);
          }
          clearTimeout(this._removeTimeout);
          this.getPane().appendChild(this._container);
          this.update();
          if (map4._fadeAnimated) {
            setOpacity(this._container, 1);
          }
          this.bringToFront();
          if (this.options.interactive) {
            addClass(this._container, "leaflet-interactive");
            this.addInteractiveTarget(this._container);
          }
        },
        onRemove: function(map4) {
          if (map4._fadeAnimated) {
            setOpacity(this._container, 0);
            this._removeTimeout = setTimeout(bind(remove2, void 0, this._container), 200);
          } else {
            remove2(this._container);
          }
          if (this.options.interactive) {
            removeClass(this._container, "leaflet-interactive");
            this.removeInteractiveTarget(this._container);
          }
        },
        // @namespace DivOverlay
        // @method getLatLng: LatLng
        // Returns the geographical point of the overlay.
        getLatLng: function() {
          return this._latlng;
        },
        // @method setLatLng(latlng: LatLng): this
        // Sets the geographical point where the overlay will open.
        setLatLng: function(latlng) {
          this._latlng = toLatLng(latlng);
          if (this._map) {
            this._updatePosition();
            this._adjustPan();
          }
          return this;
        },
        // @method getContent: String|HTMLElement
        // Returns the content of the overlay.
        getContent: function() {
          return this._content;
        },
        // @method setContent(htmlContent: String|HTMLElement|Function): this
        // Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function.
        // The function should return a `String` or `HTMLElement` to be used in the overlay.
        setContent: function(content) {
          this._content = content;
          this.update();
          return this;
        },
        // @method getElement: String|HTMLElement
        // Returns the HTML container of the overlay.
        getElement: function() {
          return this._container;
        },
        // @method update: null
        // Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded.
        update: function() {
          if (!this._map) {
            return;
          }
          this._container.style.visibility = "hidden";
          this._updateContent();
          this._updateLayout();
          this._updatePosition();
          this._container.style.visibility = "";
          this._adjustPan();
        },
        getEvents: function() {
          var events = {
            zoom: this._updatePosition,
            viewreset: this._updatePosition
          };
          if (this._zoomAnimated) {
            events.zoomanim = this._animateZoom;
          }
          return events;
        },
        // @method isOpen: Boolean
        // Returns `true` when the overlay is visible on the map.
        isOpen: function() {
          return !!this._map && this._map.hasLayer(this);
        },
        // @method bringToFront: this
        // Brings this overlay in front of other overlays (in the same map pane).
        bringToFront: function() {
          if (this._map) {
            toFront(this._container);
          }
          return this;
        },
        // @method bringToBack: this
        // Brings this overlay to the back of other overlays (in the same map pane).
        bringToBack: function() {
          if (this._map) {
            toBack(this._container);
          }
          return this;
        },
        // prepare bound overlay to open: update latlng pos / content source (for FeatureGroup)
        _prepareOpen: function(latlng) {
          var source = this._source;
          if (!source._map) {
            return false;
          }
          if (source instanceof FeatureGroup) {
            source = null;
            var layers2 = this._source._layers;
            for (var id2 in layers2) {
              if (layers2[id2]._map) {
                source = layers2[id2];
                break;
              }
            }
            if (!source) {
              return false;
            }
            this._source = source;
          }
          if (!latlng) {
            if (source.getCenter) {
              latlng = source.getCenter();
            } else if (source.getLatLng) {
              latlng = source.getLatLng();
            } else if (source.getBounds) {
              latlng = source.getBounds().getCenter();
            } else {
              throw new Error("Unable to get source layer LatLng.");
            }
          }
          this.setLatLng(latlng);
          if (this._map) {
            this.update();
          }
          return true;
        },
        _updateContent: function() {
          if (!this._content) {
            return;
          }
          var node = this._contentNode;
          var content = typeof this._content === "function" ? this._content(this._source || this) : this._content;
          if (typeof content === "string") {
            node.innerHTML = content;
          } else {
            while (node.hasChildNodes()) {
              node.removeChild(node.firstChild);
            }
            node.appendChild(content);
          }
          this.fire("contentupdate");
        },
        _updatePosition: function() {
          if (!this._map) {
            return;
          }
          var pos = this._map.latLngToLayerPoint(this._latlng), offset2 = toPoint(this.options.offset), anchor = this._getAnchor();
          if (this._zoomAnimated) {
            setPosition(this._container, pos.add(anchor));
          } else {
            offset2 = offset2.add(pos).add(anchor);
          }
          var bottom2 = this._containerBottom = -offset2.y, left2 = this._containerLeft = -Math.round(this._containerWidth / 2) + offset2.x;
          this._container.style.bottom = bottom2 + "px";
          this._container.style.left = left2 + "px";
        },
        _getAnchor: function() {
          return [0, 0];
        }
      });
      Map2.include({
        _initOverlay: function(OverlayClass, content, latlng, options) {
          var overlay = content;
          if (!(overlay instanceof OverlayClass)) {
            overlay = new OverlayClass(options).setContent(content);
          }
          if (latlng) {
            overlay.setLatLng(latlng);
          }
          return overlay;
        }
      });
      Layer.include({
        _initOverlay: function(OverlayClass, old, content, options) {
          var overlay = content;
          if (overlay instanceof OverlayClass) {
            setOptions(overlay, options);
            overlay._source = this;
          } else {
            overlay = old && !options ? old : new OverlayClass(options, this);
            overlay.setContent(content);
          }
          return overlay;
        }
      });
      var Popup = DivOverlay.extend({
        // @section
        // @aka Popup options
        options: {
          // @option pane: String = 'popupPane'
          // `Map pane` where the popup will be added.
          pane: "popupPane",
          // @option offset: Point = Point(0, 7)
          // The offset of the popup position.
          offset: [0, 7],
          // @option maxWidth: Number = 300
          // Max width of the popup, in pixels.
          maxWidth: 300,
          // @option minWidth: Number = 50
          // Min width of the popup, in pixels.
          minWidth: 50,
          // @option maxHeight: Number = null
          // If set, creates a scrollable container of the given height
          // inside a popup if its content exceeds it.
          // The scrollable container can be styled using the
          // `leaflet-popup-scrolled` CSS class selector.
          maxHeight: null,
          // @option autoPan: Boolean = true
          // Set it to `false` if you don't want the map to do panning animation
          // to fit the opened popup.
          autoPan: true,
          // @option autoPanPaddingTopLeft: Point = null
          // The margin between the popup and the top left corner of the map
          // view after autopanning was performed.
          autoPanPaddingTopLeft: null,
          // @option autoPanPaddingBottomRight: Point = null
          // The margin between the popup and the bottom right corner of the map
          // view after autopanning was performed.
          autoPanPaddingBottomRight: null,
          // @option autoPanPadding: Point = Point(5, 5)
          // Equivalent of setting both top left and bottom right autopan padding to the same value.
          autoPanPadding: [5, 5],
          // @option keepInView: Boolean = false
          // Set it to `true` if you want to prevent users from panning the popup
          // off of the screen while it is open.
          keepInView: false,
          // @option closeButton: Boolean = true
          // Controls the presence of a close button in the popup.
          closeButton: true,
          // @option autoClose: Boolean = true
          // Set it to `false` if you want to override the default behavior of
          // the popup closing when another popup is opened.
          autoClose: true,
          // @option closeOnEscapeKey: Boolean = true
          // Set it to `false` if you want to override the default behavior of
          // the ESC key for closing of the popup.
          closeOnEscapeKey: true,
          // @option closeOnClick: Boolean = *
          // Set it if you want to override the default behavior of the popup closing when user clicks
          // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
          // @option className: String = ''
          // A custom CSS class name to assign to the popup.
          className: ""
        },
        // @namespace Popup
        // @method openOn(map: Map): this
        // Alternative to `map.openPopup(popup)`.
        // Adds the popup to the map and closes the previous one.
        openOn: function(map4) {
          map4 = arguments.length ? map4 : this._source._map;
          if (!map4.hasLayer(this) && map4._popup && map4._popup.options.autoClose) {
            map4.removeLayer(map4._popup);
          }
          map4._popup = this;
          return DivOverlay.prototype.openOn.call(this, map4);
        },
        onAdd: function(map4) {
          DivOverlay.prototype.onAdd.call(this, map4);
          map4.fire("popupopen", { popup: this });
          if (this._source) {
            this._source.fire("popupopen", { popup: this }, true);
            if (!(this._source instanceof Path2)) {
              this._source.on("preclick", stopPropagation);
            }
          }
        },
        onRemove: function(map4) {
          DivOverlay.prototype.onRemove.call(this, map4);
          map4.fire("popupclose", { popup: this });
          if (this._source) {
            this._source.fire("popupclose", { popup: this }, true);
            if (!(this._source instanceof Path2)) {
              this._source.off("preclick", stopPropagation);
            }
          }
        },
        getEvents: function() {
          var events = DivOverlay.prototype.getEvents.call(this);
          if (this.options.closeOnClick !== void 0 ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
            events.preclick = this.close;
          }
          if (this.options.keepInView) {
            events.moveend = this._adjustPan;
          }
          return events;
        },
        _initLayout: function() {
          var prefix = "leaflet-popup", container = this._container = create$1(
            "div",
            prefix + " " + (this.options.className || "") + " leaflet-zoom-animated"
          );
          var wrapper = this._wrapper = create$1("div", prefix + "-content-wrapper", container);
          this._contentNode = create$1("div", prefix + "-content", wrapper);
          disableClickPropagation(container);
          disableScrollPropagation(this._contentNode);
          on(container, "contextmenu", stopPropagation);
          this._tipContainer = create$1("div", prefix + "-tip-container", container);
          this._tip = create$1("div", prefix + "-tip", this._tipContainer);
          if (this.options.closeButton) {
            var closeButton = this._closeButton = create$1("a", prefix + "-close-button", container);
            closeButton.setAttribute("role", "button");
            closeButton.setAttribute("aria-label", "Close popup");
            closeButton.href = "#close";
            closeButton.innerHTML = '<span aria-hidden="true">&#215;</span>';
            on(closeButton, "click", function(ev) {
              preventDefault(ev);
              this.close();
            }, this);
          }
        },
        _updateLayout: function() {
          var container = this._contentNode, style2 = container.style;
          style2.width = "";
          style2.whiteSpace = "nowrap";
          var width = container.offsetWidth;
          width = Math.min(width, this.options.maxWidth);
          width = Math.max(width, this.options.minWidth);
          style2.width = width + 1 + "px";
          style2.whiteSpace = "";
          style2.height = "";
          var height = container.offsetHeight, maxHeight = this.options.maxHeight, scrolledClass = "leaflet-popup-scrolled";
          if (maxHeight && height > maxHeight) {
            style2.height = maxHeight + "px";
            addClass(container, scrolledClass);
          } else {
            removeClass(container, scrolledClass);
          }
          this._containerWidth = this._container.offsetWidth;
        },
        _animateZoom: function(e) {
          var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center), anchor = this._getAnchor();
          setPosition(this._container, pos.add(anchor));
        },
        _adjustPan: function() {
          if (!this.options.autoPan) {
            return;
          }
          if (this._map._panAnim) {
            this._map._panAnim.stop();
          }
          if (this._autopanning) {
            this._autopanning = false;
            return;
          }
          var map4 = this._map, marginBottom = parseInt(getStyle(this._container, "marginBottom"), 10) || 0, containerHeight = this._container.offsetHeight + marginBottom, containerWidth = this._containerWidth, layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
          layerPos._add(getPosition(this._container));
          var containerPos = map4.layerPointToContainerPoint(layerPos), padding = toPoint(this.options.autoPanPadding), paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding), paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding), size = map4.getSize(), dx = 0, dy = 0;
          if (containerPos.x + containerWidth + paddingBR.x > size.x) {
            dx = containerPos.x + containerWidth - size.x + paddingBR.x;
          }
          if (containerPos.x - dx - paddingTL.x < 0) {
            dx = containerPos.x - paddingTL.x;
          }
          if (containerPos.y + containerHeight + paddingBR.y > size.y) {
            dy = containerPos.y + containerHeight - size.y + paddingBR.y;
          }
          if (containerPos.y - dy - paddingTL.y < 0) {
            dy = containerPos.y - paddingTL.y;
          }
          if (dx || dy) {
            if (this.options.keepInView) {
              this._autopanning = true;
            }
            map4.fire("autopanstart").panBy([dx, dy]);
          }
        },
        _getAnchor: function() {
          return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
        }
      });
      var popup = function(options, source) {
        return new Popup(options, source);
      };
      Map2.mergeOptions({
        closePopupOnClick: true
      });
      Map2.include({
        // @method openPopup(popup: Popup): this
        // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
        // @alternative
        // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
        // Creates a popup with the specified content and options and opens it in the given point on a map.
        openPopup: function(popup2, latlng, options) {
          this._initOverlay(Popup, popup2, latlng, options).openOn(this);
          return this;
        },
        // @method closePopup(popup?: Popup): this
        // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
        closePopup: function(popup2) {
          popup2 = arguments.length ? popup2 : this._popup;
          if (popup2) {
            popup2.close();
          }
          return this;
        }
      });
      Layer.include({
        // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
        // Binds a popup to the layer with the passed `content` and sets up the
        // necessary event listeners. If a `Function` is passed it will receive
        // the layer as the first argument and should return a `String` or `HTMLElement`.
        bindPopup: function(content, options) {
          this._popup = this._initOverlay(Popup, this._popup, content, options);
          if (!this._popupHandlersAdded) {
            this.on({
              click: this._openPopup,
              keypress: this._onKeyPress,
              remove: this.closePopup,
              move: this._movePopup
            });
            this._popupHandlersAdded = true;
          }
          return this;
        },
        // @method unbindPopup(): this
        // Removes the popup previously bound with `bindPopup`.
        unbindPopup: function() {
          if (this._popup) {
            this.off({
              click: this._openPopup,
              keypress: this._onKeyPress,
              remove: this.closePopup,
              move: this._movePopup
            });
            this._popupHandlersAdded = false;
            this._popup = null;
          }
          return this;
        },
        // @method openPopup(latlng?: LatLng): this
        // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
        openPopup: function(latlng) {
          if (this._popup) {
            if (!(this instanceof FeatureGroup)) {
              this._popup._source = this;
            }
            if (this._popup._prepareOpen(latlng || this._latlng)) {
              this._popup.openOn(this._map);
            }
          }
          return this;
        },
        // @method closePopup(): this
        // Closes the popup bound to this layer if it is open.
        closePopup: function() {
          if (this._popup) {
            this._popup.close();
          }
          return this;
        },
        // @method togglePopup(): this
        // Opens or closes the popup bound to this layer depending on its current state.
        togglePopup: function() {
          if (this._popup) {
            this._popup.toggle(this);
          }
          return this;
        },
        // @method isPopupOpen(): boolean
        // Returns `true` if the popup bound to this layer is currently open.
        isPopupOpen: function() {
          return this._popup ? this._popup.isOpen() : false;
        },
        // @method setPopupContent(content: String|HTMLElement|Popup): this
        // Sets the content of the popup bound to this layer.
        setPopupContent: function(content) {
          if (this._popup) {
            this._popup.setContent(content);
          }
          return this;
        },
        // @method getPopup(): Popup
        // Returns the popup bound to this layer.
        getPopup: function() {
          return this._popup;
        },
        _openPopup: function(e) {
          if (!this._popup || !this._map) {
            return;
          }
          stop(e);
          var target = e.layer || e.target;
          if (this._popup._source === target && !(target instanceof Path2)) {
            if (this._map.hasLayer(this._popup)) {
              this.closePopup();
            } else {
              this.openPopup(e.latlng);
            }
            return;
          }
          this._popup._source = target;
          this.openPopup(e.latlng);
        },
        _movePopup: function(e) {
          this._popup.setLatLng(e.latlng);
        },
        _onKeyPress: function(e) {
          if (e.originalEvent.keyCode === 13) {
            this._openPopup(e);
          }
        }
      });
      var Tooltip = DivOverlay.extend({
        // @section
        // @aka Tooltip options
        options: {
          // @option pane: String = 'tooltipPane'
          // `Map pane` where the tooltip will be added.
          pane: "tooltipPane",
          // @option offset: Point = Point(0, 0)
          // Optional offset of the tooltip position.
          offset: [0, 0],
          // @option direction: String = 'auto'
          // Direction where to open the tooltip. Possible values are: `right`, `left`,
          // `top`, `bottom`, `center`, `auto`.
          // `auto` will dynamically switch between `right` and `left` according to the tooltip
          // position on the map.
          direction: "auto",
          // @option permanent: Boolean = false
          // Whether to open the tooltip permanently or only on mouseover.
          permanent: false,
          // @option sticky: Boolean = false
          // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
          sticky: false,
          // @option opacity: Number = 0.9
          // Tooltip container opacity.
          opacity: 0.9
        },
        onAdd: function(map4) {
          DivOverlay.prototype.onAdd.call(this, map4);
          this.setOpacity(this.options.opacity);
          map4.fire("tooltipopen", { tooltip: this });
          if (this._source) {
            this.addEventParent(this._source);
            this._source.fire("tooltipopen", { tooltip: this }, true);
          }
        },
        onRemove: function(map4) {
          DivOverlay.prototype.onRemove.call(this, map4);
          map4.fire("tooltipclose", { tooltip: this });
          if (this._source) {
            this.removeEventParent(this._source);
            this._source.fire("tooltipclose", { tooltip: this }, true);
          }
        },
        getEvents: function() {
          var events = DivOverlay.prototype.getEvents.call(this);
          if (!this.options.permanent) {
            events.preclick = this.close;
          }
          return events;
        },
        _initLayout: function() {
          var prefix = "leaflet-tooltip", className = prefix + " " + (this.options.className || "") + " leaflet-zoom-" + (this._zoomAnimated ? "animated" : "hide");
          this._contentNode = this._container = create$1("div", className);
          this._container.setAttribute("role", "tooltip");
          this._container.setAttribute("id", "leaflet-tooltip-" + stamp(this));
        },
        _updateLayout: function() {
        },
        _adjustPan: function() {
        },
        _setPosition: function(pos) {
          var subX, subY, map4 = this._map, container = this._container, centerPoint = map4.latLngToContainerPoint(map4.getCenter()), tooltipPoint = map4.layerPointToContainerPoint(pos), direction = this.options.direction, tooltipWidth = container.offsetWidth, tooltipHeight = container.offsetHeight, offset2 = toPoint(this.options.offset), anchor = this._getAnchor();
          if (direction === "top") {
            subX = tooltipWidth / 2;
            subY = tooltipHeight;
          } else if (direction === "bottom") {
            subX = tooltipWidth / 2;
            subY = 0;
          } else if (direction === "center") {
            subX = tooltipWidth / 2;
            subY = tooltipHeight / 2;
          } else if (direction === "right") {
            subX = 0;
            subY = tooltipHeight / 2;
          } else if (direction === "left") {
            subX = tooltipWidth;
            subY = tooltipHeight / 2;
          } else if (tooltipPoint.x < centerPoint.x) {
            direction = "right";
            subX = 0;
            subY = tooltipHeight / 2;
          } else {
            direction = "left";
            subX = tooltipWidth + (offset2.x + anchor.x) * 2;
            subY = tooltipHeight / 2;
          }
          pos = pos.subtract(toPoint(subX, subY, true)).add(offset2).add(anchor);
          removeClass(container, "leaflet-tooltip-right");
          removeClass(container, "leaflet-tooltip-left");
          removeClass(container, "leaflet-tooltip-top");
          removeClass(container, "leaflet-tooltip-bottom");
          addClass(container, "leaflet-tooltip-" + direction);
          setPosition(container, pos);
        },
        _updatePosition: function() {
          var pos = this._map.latLngToLayerPoint(this._latlng);
          this._setPosition(pos);
        },
        setOpacity: function(opacity) {
          this.options.opacity = opacity;
          if (this._container) {
            setOpacity(this._container, opacity);
          }
        },
        _animateZoom: function(e) {
          var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
          this._setPosition(pos);
        },
        _getAnchor: function() {
          return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
        }
      });
      var tooltip = function(options, source) {
        return new Tooltip(options, source);
      };
      Map2.include({
        // @method openTooltip(tooltip: Tooltip): this
        // Opens the specified tooltip.
        // @alternative
        // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
        // Creates a tooltip with the specified content and options and open it.
        openTooltip: function(tooltip2, latlng, options) {
          this._initOverlay(Tooltip, tooltip2, latlng, options).openOn(this);
          return this;
        },
        // @method closeTooltip(tooltip: Tooltip): this
        // Closes the tooltip given as parameter.
        closeTooltip: function(tooltip2) {
          tooltip2.close();
          return this;
        }
      });
      Layer.include({
        // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
        // Binds a tooltip to the layer with the passed `content` and sets up the
        // necessary event listeners. If a `Function` is passed it will receive
        // the layer as the first argument and should return a `String` or `HTMLElement`.
        bindTooltip: function(content, options) {
          if (this._tooltip && this.isTooltipOpen()) {
            this.unbindTooltip();
          }
          this._tooltip = this._initOverlay(Tooltip, this._tooltip, content, options);
          this._initTooltipInteractions();
          if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
            this.openTooltip();
          }
          return this;
        },
        // @method unbindTooltip(): this
        // Removes the tooltip previously bound with `bindTooltip`.
        unbindTooltip: function() {
          if (this._tooltip) {
            this._initTooltipInteractions(true);
            this.closeTooltip();
            this._tooltip = null;
          }
          return this;
        },
        _initTooltipInteractions: function(remove3) {
          if (!remove3 && this._tooltipHandlersAdded) {
            return;
          }
          var onOff = remove3 ? "off" : "on", events = {
            remove: this.closeTooltip,
            move: this._moveTooltip
          };
          if (!this._tooltip.options.permanent) {
            events.mouseover = this._openTooltip;
            events.mouseout = this.closeTooltip;
            events.click = this._openTooltip;
            if (this._map) {
              this._addFocusListeners();
            } else {
              events.add = this._addFocusListeners;
            }
          } else {
            events.add = this._openTooltip;
          }
          if (this._tooltip.options.sticky) {
            events.mousemove = this._moveTooltip;
          }
          this[onOff](events);
          this._tooltipHandlersAdded = !remove3;
        },
        // @method openTooltip(latlng?: LatLng): this
        // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
        openTooltip: function(latlng) {
          if (this._tooltip) {
            if (!(this instanceof FeatureGroup)) {
              this._tooltip._source = this;
            }
            if (this._tooltip._prepareOpen(latlng)) {
              this._tooltip.openOn(this._map);
              if (this.getElement) {
                this._setAriaDescribedByOnLayer(this);
              } else if (this.eachLayer) {
                this.eachLayer(this._setAriaDescribedByOnLayer, this);
              }
            }
          }
          return this;
        },
        // @method closeTooltip(): this
        // Closes the tooltip bound to this layer if it is open.
        closeTooltip: function() {
          if (this._tooltip) {
            return this._tooltip.close();
          }
        },
        // @method toggleTooltip(): this
        // Opens or closes the tooltip bound to this layer depending on its current state.
        toggleTooltip: function() {
          if (this._tooltip) {
            this._tooltip.toggle(this);
          }
          return this;
        },
        // @method isTooltipOpen(): boolean
        // Returns `true` if the tooltip bound to this layer is currently open.
        isTooltipOpen: function() {
          return this._tooltip.isOpen();
        },
        // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
        // Sets the content of the tooltip bound to this layer.
        setTooltipContent: function(content) {
          if (this._tooltip) {
            this._tooltip.setContent(content);
          }
          return this;
        },
        // @method getTooltip(): Tooltip
        // Returns the tooltip bound to this layer.
        getTooltip: function() {
          return this._tooltip;
        },
        _addFocusListeners: function() {
          if (this.getElement) {
            this._addFocusListenersOnLayer(this);
          } else if (this.eachLayer) {
            this.eachLayer(this._addFocusListenersOnLayer, this);
          }
        },
        _addFocusListenersOnLayer: function(layer) {
          var el = typeof layer.getElement === "function" && layer.getElement();
          if (el) {
            on(el, "focus", function() {
              this._tooltip._source = layer;
              this.openTooltip();
            }, this);
            on(el, "blur", this.closeTooltip, this);
          }
        },
        _setAriaDescribedByOnLayer: function(layer) {
          var el = typeof layer.getElement === "function" && layer.getElement();
          if (el) {
            el.setAttribute("aria-describedby", this._tooltip._container.id);
          }
        },
        _openTooltip: function(e) {
          if (!this._tooltip || !this._map) {
            return;
          }
          if (this._map.dragging && this._map.dragging.moving() && !this._openOnceFlag) {
            this._openOnceFlag = true;
            var that = this;
            this._map.once("moveend", function() {
              that._openOnceFlag = false;
              that._openTooltip(e);
            });
            return;
          }
          this._tooltip._source = e.layer || e.target;
          this.openTooltip(this._tooltip.options.sticky ? e.latlng : void 0);
        },
        _moveTooltip: function(e) {
          var latlng = e.latlng, containerPoint, layerPoint;
          if (this._tooltip.options.sticky && e.originalEvent) {
            containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
            layerPoint = this._map.containerPointToLayerPoint(containerPoint);
            latlng = this._map.layerPointToLatLng(layerPoint);
          }
          this._tooltip.setLatLng(latlng);
        }
      });
      var DivIcon = Icon.extend({
        options: {
          // @section
          // @aka DivIcon options
          iconSize: [12, 12],
          // also can be set through CSS
          // iconAnchor: (Point),
          // popupAnchor: (Point),
          // @option html: String|HTMLElement = ''
          // Custom HTML code to put inside the div element, empty by default. Alternatively,
          // an instance of `HTMLElement`.
          html: false,
          // @option bgPos: Point = [0, 0]
          // Optional relative position of the background, in pixels
          bgPos: null,
          className: "leaflet-div-icon"
        },
        createIcon: function(oldIcon) {
          var div = oldIcon && oldIcon.tagName === "DIV" ? oldIcon : document.createElement("div"), options = this.options;
          if (options.html instanceof Element) {
            empty2(div);
            div.appendChild(options.html);
          } else {
            div.innerHTML = options.html !== false ? options.html : "";
          }
          if (options.bgPos) {
            var bgPos = toPoint(options.bgPos);
            div.style.backgroundPosition = -bgPos.x + "px " + -bgPos.y + "px";
          }
          this._setIconStyles(div, "icon");
          return div;
        },
        createShadow: function() {
          return null;
        }
      });
      function divIcon2(options) {
        return new DivIcon(options);
      }
      Icon.Default = IconDefault;
      var GridLayer = Layer.extend({
        // @section
        // @aka GridLayer options
        options: {
          // @option tileSize: Number|Point = 256
          // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
          tileSize: 256,
          // @option opacity: Number = 1.0
          // Opacity of the tiles. Can be used in the `createTile()` function.
          opacity: 1,
          // @option updateWhenIdle: Boolean = (depends)
          // Load new tiles only when panning ends.
          // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
          // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
          // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
          updateWhenIdle: Browser.mobile,
          // @option updateWhenZooming: Boolean = true
          // By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends.
          updateWhenZooming: true,
          // @option updateInterval: Number = 200
          // Tiles will not update more than once every `updateInterval` milliseconds when panning.
          updateInterval: 200,
          // @option zIndex: Number = 1
          // The explicit zIndex of the tile layer.
          zIndex: 1,
          // @option bounds: LatLngBounds = undefined
          // If set, tiles will only be loaded inside the set `LatLngBounds`.
          bounds: null,
          // @option minZoom: Number = 0
          // The minimum zoom level down to which this layer will be displayed (inclusive).
          minZoom: 0,
          // @option maxZoom: Number = undefined
          // The maximum zoom level up to which this layer will be displayed (inclusive).
          maxZoom: void 0,
          // @option maxNativeZoom: Number = undefined
          // Maximum zoom number the tile source has available. If it is specified,
          // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
          // from `maxNativeZoom` level and auto-scaled.
          maxNativeZoom: void 0,
          // @option minNativeZoom: Number = undefined
          // Minimum zoom number the tile source has available. If it is specified,
          // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
          // from `minNativeZoom` level and auto-scaled.
          minNativeZoom: void 0,
          // @option noWrap: Boolean = false
          // Whether the layer is wrapped around the antimeridian. If `true`, the
          // GridLayer will only be displayed once at low zoom levels. Has no
          // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
          // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
          // tiles outside the CRS limits.
          noWrap: false,
          // @option pane: String = 'tilePane'
          // `Map pane` where the grid layer will be added.
          pane: "tilePane",
          // @option className: String = ''
          // A custom class name to assign to the tile layer. Empty by default.
          className: "",
          // @option keepBuffer: Number = 2
          // When panning the map, keep this many rows and columns of tiles before unloading them.
          keepBuffer: 2
        },
        initialize: function(options) {
          setOptions(this, options);
        },
        onAdd: function() {
          this._initContainer();
          this._levels = {};
          this._tiles = {};
          this._resetView();
        },
        beforeAdd: function(map4) {
          map4._addZoomLimit(this);
        },
        onRemove: function(map4) {
          this._removeAllTiles();
          remove2(this._container);
          map4._removeZoomLimit(this);
          this._container = null;
          this._tileZoom = void 0;
        },
        // @method bringToFront: this
        // Brings the tile layer to the top of all tile layers.
        bringToFront: function() {
          if (this._map) {
            toFront(this._container);
            this._setAutoZIndex(Math.max);
          }
          return this;
        },
        // @method bringToBack: this
        // Brings the tile layer to the bottom of all tile layers.
        bringToBack: function() {
          if (this._map) {
            toBack(this._container);
            this._setAutoZIndex(Math.min);
          }
          return this;
        },
        // @method getContainer: HTMLElement
        // Returns the HTML element that contains the tiles for this layer.
        getContainer: function() {
          return this._container;
        },
        // @method setOpacity(opacity: Number): this
        // Changes the [opacity](#gridlayer-opacity) of the grid layer.
        setOpacity: function(opacity) {
          this.options.opacity = opacity;
          this._updateOpacity();
          return this;
        },
        // @method setZIndex(zIndex: Number): this
        // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
        setZIndex: function(zIndex) {
          this.options.zIndex = zIndex;
          this._updateZIndex();
          return this;
        },
        // @method isLoading: Boolean
        // Returns `true` if any tile in the grid layer has not finished loading.
        isLoading: function() {
          return this._loading;
        },
        // @method redraw: this
        // Causes the layer to clear all the tiles and request them again.
        redraw: function() {
          if (this._map) {
            this._removeAllTiles();
            var tileZoom = this._clampZoom(this._map.getZoom());
            if (tileZoom !== this._tileZoom) {
              this._tileZoom = tileZoom;
              this._updateLevels();
            }
            this._update();
          }
          return this;
        },
        getEvents: function() {
          var events = {
            viewprereset: this._invalidateAll,
            viewreset: this._resetView,
            zoom: this._resetView,
            moveend: this._onMoveEnd
          };
          if (!this.options.updateWhenIdle) {
            if (!this._onMove) {
              this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
            }
            events.move = this._onMove;
          }
          if (this._zoomAnimated) {
            events.zoomanim = this._animateZoom;
          }
          return events;
        },
        // @section Extension methods
        // Layers extending `GridLayer` shall reimplement the following method.
        // @method createTile(coords: Object, done?: Function): HTMLElement
        // Called only internally, must be overridden by classes extending `GridLayer`.
        // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
        // is specified, it must be called when the tile has finished loading and drawing.
        createTile: function() {
          return document.createElement("div");
        },
        // @section
        // @method getTileSize: Point
        // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
        getTileSize: function() {
          var s2 = this.options.tileSize;
          return s2 instanceof Point ? s2 : new Point(s2, s2);
        },
        _updateZIndex: function() {
          if (this._container && this.options.zIndex !== void 0 && this.options.zIndex !== null) {
            this._container.style.zIndex = this.options.zIndex;
          }
        },
        _setAutoZIndex: function(compare) {
          var layers2 = this.getPane().children, edgeZIndex = -compare(-Infinity, Infinity);
          for (var i = 0, len = layers2.length, zIndex; i < len; i++) {
            zIndex = layers2[i].style.zIndex;
            if (layers2[i] !== this._container && zIndex) {
              edgeZIndex = compare(edgeZIndex, +zIndex);
            }
          }
          if (isFinite(edgeZIndex)) {
            this.options.zIndex = edgeZIndex + compare(-1, 1);
            this._updateZIndex();
          }
        },
        _updateOpacity: function() {
          if (!this._map) {
            return;
          }
          if (Browser.ielt9) {
            return;
          }
          setOpacity(this._container, this.options.opacity);
          var now3 = +/* @__PURE__ */ new Date(), nextFrame = false, willPrune = false;
          for (var key in this._tiles) {
            var tile = this._tiles[key];
            if (!tile.current || !tile.loaded) {
              continue;
            }
            var fade = Math.min(1, (now3 - tile.loaded) / 200);
            setOpacity(tile.el, fade);
            if (fade < 1) {
              nextFrame = true;
            } else {
              if (tile.active) {
                willPrune = true;
              } else {
                this._onOpaqueTile(tile);
              }
              tile.active = true;
            }
          }
          if (willPrune && !this._noPrune) {
            this._pruneTiles();
          }
          if (nextFrame) {
            cancelAnimFrame(this._fadeFrame);
            this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
          }
        },
        _onOpaqueTile: falseFn,
        _initContainer: function() {
          if (this._container) {
            return;
          }
          this._container = create$1("div", "leaflet-layer " + (this.options.className || ""));
          this._updateZIndex();
          if (this.options.opacity < 1) {
            this._updateOpacity();
          }
          this.getPane().appendChild(this._container);
        },
        _updateLevels: function() {
          var zoom2 = this._tileZoom, maxZoom = this.options.maxZoom;
          if (zoom2 === void 0) {
            return void 0;
          }
          for (var z2 in this._levels) {
            z2 = Number(z2);
            if (this._levels[z2].el.children.length || z2 === zoom2) {
              this._levels[z2].el.style.zIndex = maxZoom - Math.abs(zoom2 - z2);
              this._onUpdateLevel(z2);
            } else {
              remove2(this._levels[z2].el);
              this._removeTilesAtZoom(z2);
              this._onRemoveLevel(z2);
              delete this._levels[z2];
            }
          }
          var level = this._levels[zoom2], map4 = this._map;
          if (!level) {
            level = this._levels[zoom2] = {};
            level.el = create$1("div", "leaflet-tile-container leaflet-zoom-animated", this._container);
            level.el.style.zIndex = maxZoom;
            level.origin = map4.project(map4.unproject(map4.getPixelOrigin()), zoom2).round();
            level.zoom = zoom2;
            this._setZoomTransform(level, map4.getCenter(), map4.getZoom());
            falseFn(level.el.offsetWidth);
            this._onCreateLevel(level);
          }
          this._level = level;
          return level;
        },
        _onUpdateLevel: falseFn,
        _onRemoveLevel: falseFn,
        _onCreateLevel: falseFn,
        _pruneTiles: function() {
          if (!this._map) {
            return;
          }
          var key, tile;
          var zoom2 = this._map.getZoom();
          if (zoom2 > this.options.maxZoom || zoom2 < this.options.minZoom) {
            this._removeAllTiles();
            return;
          }
          for (key in this._tiles) {
            tile = this._tiles[key];
            tile.retain = tile.current;
          }
          for (key in this._tiles) {
            tile = this._tiles[key];
            if (tile.current && !tile.active) {
              var coords = tile.coords;
              if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
                this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
              }
            }
          }
          for (key in this._tiles) {
            if (!this._tiles[key].retain) {
              this._removeTile(key);
            }
          }
        },
        _removeTilesAtZoom: function(zoom2) {
          for (var key in this._tiles) {
            if (this._tiles[key].coords.z !== zoom2) {
              continue;
            }
            this._removeTile(key);
          }
        },
        _removeAllTiles: function() {
          for (var key in this._tiles) {
            this._removeTile(key);
          }
        },
        _invalidateAll: function() {
          for (var z2 in this._levels) {
            remove2(this._levels[z2].el);
            this._onRemoveLevel(Number(z2));
            delete this._levels[z2];
          }
          this._removeAllTiles();
          this._tileZoom = void 0;
        },
        _retainParent: function(x2, y2, z2, minZoom) {
          var x22 = Math.floor(x2 / 2), y22 = Math.floor(y2 / 2), z22 = z2 - 1, coords2 = new Point(+x22, +y22);
          coords2.z = +z22;
          var key = this._tileCoordsToKey(coords2), tile = this._tiles[key];
          if (tile && tile.active) {
            tile.retain = true;
            return true;
          } else if (tile && tile.loaded) {
            tile.retain = true;
          }
          if (z22 > minZoom) {
            return this._retainParent(x22, y22, z22, minZoom);
          }
          return false;
        },
        _retainChildren: function(x2, y2, z2, maxZoom) {
          for (var i = 2 * x2; i < 2 * x2 + 2; i++) {
            for (var j = 2 * y2; j < 2 * y2 + 2; j++) {
              var coords = new Point(i, j);
              coords.z = z2 + 1;
              var key = this._tileCoordsToKey(coords), tile = this._tiles[key];
              if (tile && tile.active) {
                tile.retain = true;
                continue;
              } else if (tile && tile.loaded) {
                tile.retain = true;
              }
              if (z2 + 1 < maxZoom) {
                this._retainChildren(i, j, z2 + 1, maxZoom);
              }
            }
          }
        },
        _resetView: function(e) {
          var animating = e && (e.pinch || e.flyTo);
          this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
        },
        _animateZoom: function(e) {
          this._setView(e.center, e.zoom, true, e.noUpdate);
        },
        _clampZoom: function(zoom2) {
          var options = this.options;
          if (void 0 !== options.minNativeZoom && zoom2 < options.minNativeZoom) {
            return options.minNativeZoom;
          }
          if (void 0 !== options.maxNativeZoom && options.maxNativeZoom < zoom2) {
            return options.maxNativeZoom;
          }
          return zoom2;
        },
        _setView: function(center2, zoom2, noPrune, noUpdate) {
          var tileZoom = Math.round(zoom2);
          if (this.options.maxZoom !== void 0 && tileZoom > this.options.maxZoom || this.options.minZoom !== void 0 && tileZoom < this.options.minZoom) {
            tileZoom = void 0;
          } else {
            tileZoom = this._clampZoom(tileZoom);
          }
          var tileZoomChanged = this.options.updateWhenZooming && tileZoom !== this._tileZoom;
          if (!noUpdate || tileZoomChanged) {
            this._tileZoom = tileZoom;
            if (this._abortLoading) {
              this._abortLoading();
            }
            this._updateLevels();
            this._resetGrid();
            if (tileZoom !== void 0) {
              this._update(center2);
            }
            if (!noPrune) {
              this._pruneTiles();
            }
            this._noPrune = !!noPrune;
          }
          this._setZoomTransforms(center2, zoom2);
        },
        _setZoomTransforms: function(center2, zoom2) {
          for (var i in this._levels) {
            this._setZoomTransform(this._levels[i], center2, zoom2);
          }
        },
        _setZoomTransform: function(level, center2, zoom2) {
          var scale2 = this._map.getZoomScale(zoom2, level.zoom), translate = level.origin.multiplyBy(scale2).subtract(this._map._getNewPixelOrigin(center2, zoom2)).round();
          if (Browser.any3d) {
            setTransform(level.el, translate, scale2);
          } else {
            setPosition(level.el, translate);
          }
        },
        _resetGrid: function() {
          var map4 = this._map, crs = map4.options.crs, tileSize = this._tileSize = this.getTileSize(), tileZoom = this._tileZoom;
          var bounds = this._map.getPixelWorldBounds(this._tileZoom);
          if (bounds) {
            this._globalTileRange = this._pxBoundsToTileRange(bounds);
          }
          this._wrapX = crs.wrapLng && !this.options.noWrap && [
            Math.floor(map4.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
            Math.ceil(map4.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
          ];
          this._wrapY = crs.wrapLat && !this.options.noWrap && [
            Math.floor(map4.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
            Math.ceil(map4.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
          ];
        },
        _onMoveEnd: function() {
          if (!this._map || this._map._animatingZoom) {
            return;
          }
          this._update();
        },
        _getTiledPixelBounds: function(center2) {
          var map4 = this._map, mapZoom = map4._animatingZoom ? Math.max(map4._animateToZoom, map4.getZoom()) : map4.getZoom(), scale2 = map4.getZoomScale(mapZoom, this._tileZoom), pixelCenter = map4.project(center2, this._tileZoom).floor(), halfSize = map4.getSize().divideBy(scale2 * 2);
          return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
        },
        // Private method to load tiles in the grid's active zoom level according to map bounds
        _update: function(center2) {
          var map4 = this._map;
          if (!map4) {
            return;
          }
          var zoom2 = this._clampZoom(map4.getZoom());
          if (center2 === void 0) {
            center2 = map4.getCenter();
          }
          if (this._tileZoom === void 0) {
            return;
          }
          var pixelBounds = this._getTiledPixelBounds(center2), tileRange = this._pxBoundsToTileRange(pixelBounds), tileCenter = tileRange.getCenter(), queue = [], margin = this.options.keepBuffer, noPruneRange = new Bounds(
            tileRange.getBottomLeft().subtract([margin, -margin]),
            tileRange.getTopRight().add([margin, -margin])
          );
          if (!(isFinite(tileRange.min.x) && isFinite(tileRange.min.y) && isFinite(tileRange.max.x) && isFinite(tileRange.max.y))) {
            throw new Error("Attempted to load an infinite number of tiles");
          }
          for (var key in this._tiles) {
            var c = this._tiles[key].coords;
            if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
              this._tiles[key].current = false;
            }
          }
          if (Math.abs(zoom2 - this._tileZoom) > 1) {
            this._setView(center2, zoom2);
            return;
          }
          for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
            for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
              var coords = new Point(i, j);
              coords.z = this._tileZoom;
              if (!this._isValidTile(coords)) {
                continue;
              }
              var tile = this._tiles[this._tileCoordsToKey(coords)];
              if (tile) {
                tile.current = true;
              } else {
                queue.push(coords);
              }
            }
          }
          queue.sort(function(a, b) {
            return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
          });
          if (queue.length !== 0) {
            if (!this._loading) {
              this._loading = true;
              this.fire("loading");
            }
            var fragment = document.createDocumentFragment();
            for (i = 0; i < queue.length; i++) {
              this._addTile(queue[i], fragment);
            }
            this._level.el.appendChild(fragment);
          }
        },
        _isValidTile: function(coords) {
          var crs = this._map.options.crs;
          if (!crs.infinite) {
            var bounds = this._globalTileRange;
            if (!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x) || !crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y)) {
              return false;
            }
          }
          if (!this.options.bounds) {
            return true;
          }
          var tileBounds = this._tileCoordsToBounds(coords);
          return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
        },
        _keyToBounds: function(key) {
          return this._tileCoordsToBounds(this._keyToTileCoords(key));
        },
        _tileCoordsToNwSe: function(coords) {
          var map4 = this._map, tileSize = this.getTileSize(), nwPoint = coords.scaleBy(tileSize), sePoint = nwPoint.add(tileSize), nw = map4.unproject(nwPoint, coords.z), se = map4.unproject(sePoint, coords.z);
          return [nw, se];
        },
        // converts tile coordinates to its geographical bounds
        _tileCoordsToBounds: function(coords) {
          var bp = this._tileCoordsToNwSe(coords), bounds = new LatLngBounds(bp[0], bp[1]);
          if (!this.options.noWrap) {
            bounds = this._map.wrapLatLngBounds(bounds);
          }
          return bounds;
        },
        // converts tile coordinates to key for the tile cache
        _tileCoordsToKey: function(coords) {
          return coords.x + ":" + coords.y + ":" + coords.z;
        },
        // converts tile cache key to coordinates
        _keyToTileCoords: function(key) {
          var k = key.split(":"), coords = new Point(+k[0], +k[1]);
          coords.z = +k[2];
          return coords;
        },
        _removeTile: function(key) {
          var tile = this._tiles[key];
          if (!tile) {
            return;
          }
          remove2(tile.el);
          delete this._tiles[key];
          this.fire("tileunload", {
            tile: tile.el,
            coords: this._keyToTileCoords(key)
          });
        },
        _initTile: function(tile) {
          addClass(tile, "leaflet-tile");
          var tileSize = this.getTileSize();
          tile.style.width = tileSize.x + "px";
          tile.style.height = tileSize.y + "px";
          tile.onselectstart = falseFn;
          tile.onmousemove = falseFn;
          if (Browser.ielt9 && this.options.opacity < 1) {
            setOpacity(tile, this.options.opacity);
          }
        },
        _addTile: function(coords, container) {
          var tilePos = this._getTilePos(coords), key = this._tileCoordsToKey(coords);
          var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
          this._initTile(tile);
          if (this.createTile.length < 2) {
            requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
          }
          setPosition(tile, tilePos);
          this._tiles[key] = {
            el: tile,
            coords,
            current: true
          };
          container.appendChild(tile);
          this.fire("tileloadstart", {
            tile,
            coords
          });
        },
        _tileReady: function(coords, err, tile) {
          if (err) {
            this.fire("tileerror", {
              error: err,
              tile,
              coords
            });
          }
          var key = this._tileCoordsToKey(coords);
          tile = this._tiles[key];
          if (!tile) {
            return;
          }
          tile.loaded = +/* @__PURE__ */ new Date();
          if (this._map._fadeAnimated) {
            setOpacity(tile.el, 0);
            cancelAnimFrame(this._fadeFrame);
            this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
          } else {
            tile.active = true;
            this._pruneTiles();
          }
          if (!err) {
            addClass(tile.el, "leaflet-tile-loaded");
            this.fire("tileload", {
              tile: tile.el,
              coords
            });
          }
          if (this._noTilesToLoad()) {
            this._loading = false;
            this.fire("load");
            if (Browser.ielt9 || !this._map._fadeAnimated) {
              requestAnimFrame(this._pruneTiles, this);
            } else {
              setTimeout(bind(this._pruneTiles, this), 250);
            }
          }
        },
        _getTilePos: function(coords) {
          return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
        },
        _wrapCoords: function(coords) {
          var newCoords = new Point(
            this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
            this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y
          );
          newCoords.z = coords.z;
          return newCoords;
        },
        _pxBoundsToTileRange: function(bounds) {
          var tileSize = this.getTileSize();
          return new Bounds(
            bounds.min.unscaleBy(tileSize).floor(),
            bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1])
          );
        },
        _noTilesToLoad: function() {
          for (var key in this._tiles) {
            if (!this._tiles[key].loaded) {
              return false;
            }
          }
          return true;
        }
      });
      function gridLayer(options) {
        return new GridLayer(options);
      }
      var TileLayer = GridLayer.extend({
        // @section
        // @aka TileLayer options
        options: {
          // @option minZoom: Number = 0
          // The minimum zoom level down to which this layer will be displayed (inclusive).
          minZoom: 0,
          // @option maxZoom: Number = 18
          // The maximum zoom level up to which this layer will be displayed (inclusive).
          maxZoom: 18,
          // @option subdomains: String|String[] = 'abc'
          // Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.
          subdomains: "abc",
          // @option errorTileUrl: String = ''
          // URL to the tile image to show in place of the tile that failed to load.
          errorTileUrl: "",
          // @option zoomOffset: Number = 0
          // The zoom number used in tile URLs will be offset with this value.
          zoomOffset: 0,
          // @option tms: Boolean = false
          // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
          tms: false,
          // @option zoomReverse: Boolean = false
          // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
          zoomReverse: false,
          // @option detectRetina: Boolean = false
          // If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.
          detectRetina: false,
          // @option crossOrigin: Boolean|String = false
          // Whether the crossOrigin attribute will be added to the tiles.
          // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
          // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
          crossOrigin: false,
          // @option referrerPolicy: Boolean|String = false
          // Whether the referrerPolicy attribute will be added to the tiles.
          // If a String is provided, all tiles will have their referrerPolicy attribute set to the String provided.
          // This may be needed if your map's rendering context has a strict default but your tile provider expects a valid referrer
          // (e.g. to validate an API token).
          // Refer to [HTMLImageElement.referrerPolicy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/referrerPolicy) for valid String values.
          referrerPolicy: false
        },
        initialize: function(url2, options) {
          this._url = url2;
          options = setOptions(this, options);
          if (options.detectRetina && Browser.retina && options.maxZoom > 0) {
            options.tileSize = Math.floor(options.tileSize / 2);
            if (!options.zoomReverse) {
              options.zoomOffset++;
              options.maxZoom = Math.max(options.minZoom, options.maxZoom - 1);
            } else {
              options.zoomOffset--;
              options.minZoom = Math.min(options.maxZoom, options.minZoom + 1);
            }
            options.minZoom = Math.max(0, options.minZoom);
          } else if (!options.zoomReverse) {
            options.maxZoom = Math.max(options.minZoom, options.maxZoom);
          } else {
            options.minZoom = Math.min(options.maxZoom, options.minZoom);
          }
          if (typeof options.subdomains === "string") {
            options.subdomains = options.subdomains.split("");
          }
          this.on("tileunload", this._onTileRemove);
        },
        // @method setUrl(url: String, noRedraw?: Boolean): this
        // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
        // If the URL does not change, the layer will not be redrawn unless
        // the noRedraw parameter is set to false.
        setUrl: function(url2, noRedraw) {
          if (this._url === url2 && noRedraw === void 0) {
            noRedraw = true;
          }
          this._url = url2;
          if (!noRedraw) {
            this.redraw();
          }
          return this;
        },
        // @method createTile(coords: Object, done?: Function): HTMLElement
        // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
        // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
        // callback is called when the tile has been loaded.
        createTile: function(coords, done) {
          var tile = document.createElement("img");
          on(tile, "load", bind(this._tileOnLoad, this, done, tile));
          on(tile, "error", bind(this._tileOnError, this, done, tile));
          if (this.options.crossOrigin || this.options.crossOrigin === "") {
            tile.crossOrigin = this.options.crossOrigin === true ? "" : this.options.crossOrigin;
          }
          if (typeof this.options.referrerPolicy === "string") {
            tile.referrerPolicy = this.options.referrerPolicy;
          }
          tile.alt = "";
          tile.src = this.getTileUrl(coords);
          return tile;
        },
        // @section Extension methods
        // @uninheritable
        // Layers extending `TileLayer` might reimplement the following method.
        // @method getTileUrl(coords: Object): String
        // Called only internally, returns the URL for a tile given its coordinates.
        // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
        getTileUrl: function(coords) {
          var data = {
            r: Browser.retina ? "@2x" : "",
            s: this._getSubdomain(coords),
            x: coords.x,
            y: coords.y,
            z: this._getZoomForUrl()
          };
          if (this._map && !this._map.options.crs.infinite) {
            var invertedY = this._globalTileRange.max.y - coords.y;
            if (this.options.tms) {
              data["y"] = invertedY;
            }
            data["-y"] = invertedY;
          }
          return template(this._url, extend3(data, this.options));
        },
        _tileOnLoad: function(done, tile) {
          if (Browser.ielt9) {
            setTimeout(bind(done, this, null, tile), 0);
          } else {
            done(null, tile);
          }
        },
        _tileOnError: function(done, tile, e) {
          var errorUrl = this.options.errorTileUrl;
          if (errorUrl && tile.getAttribute("src") !== errorUrl) {
            tile.src = errorUrl;
          }
          done(e, tile);
        },
        _onTileRemove: function(e) {
          e.tile.onload = null;
        },
        _getZoomForUrl: function() {
          var zoom2 = this._tileZoom, maxZoom = this.options.maxZoom, zoomReverse = this.options.zoomReverse, zoomOffset = this.options.zoomOffset;
          if (zoomReverse) {
            zoom2 = maxZoom - zoom2;
          }
          return zoom2 + zoomOffset;
        },
        _getSubdomain: function(tilePoint) {
          var index2 = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
          return this.options.subdomains[index2];
        },
        // stops loading all tiles in the background layer
        _abortLoading: function() {
          var i, tile;
          for (i in this._tiles) {
            if (this._tiles[i].coords.z !== this._tileZoom) {
              tile = this._tiles[i].el;
              tile.onload = falseFn;
              tile.onerror = falseFn;
              if (!tile.complete) {
                tile.src = emptyImageUrl;
                var coords = this._tiles[i].coords;
                remove2(tile);
                delete this._tiles[i];
                this.fire("tileabort", {
                  tile,
                  coords
                });
              }
            }
          }
        },
        _removeTile: function(key) {
          var tile = this._tiles[key];
          if (!tile) {
            return;
          }
          tile.el.setAttribute("src", emptyImageUrl);
          return GridLayer.prototype._removeTile.call(this, key);
        },
        _tileReady: function(coords, err, tile) {
          if (!this._map || tile && tile.getAttribute("src") === emptyImageUrl) {
            return;
          }
          return GridLayer.prototype._tileReady.call(this, coords, err, tile);
        }
      });
      function tileLayer2(url2, options) {
        return new TileLayer(url2, options);
      }
      var TileLayerWMS = TileLayer.extend({
        // @section
        // @aka TileLayer.WMS options
        // If any custom options not documented here are used, they will be sent to the
        // WMS server as extra parameters in each request URL. This can be useful for
        // [non-standard vendor WMS parameters](https://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
        defaultWmsParams: {
          service: "WMS",
          request: "GetMap",
          // @option layers: String = ''
          // **(required)** Comma-separated list of WMS layers to show.
          layers: "",
          // @option styles: String = ''
          // Comma-separated list of WMS styles.
          styles: "",
          // @option format: String = 'image/jpeg'
          // WMS image format (use `'image/png'` for layers with transparency).
          format: "image/jpeg",
          // @option transparent: Boolean = false
          // If `true`, the WMS service will return images with transparency.
          transparent: false,
          // @option version: String = '1.1.1'
          // Version of the WMS service to use
          version: "1.1.1"
        },
        options: {
          // @option crs: CRS = null
          // Coordinate Reference System to use for the WMS requests, defaults to
          // map CRS. Don't change this if you're not sure what it means.
          crs: null,
          // @option uppercase: Boolean = false
          // If `true`, WMS request parameter keys will be uppercase.
          uppercase: false
        },
        initialize: function(url2, options) {
          this._url = url2;
          var wmsParams = extend3({}, this.defaultWmsParams);
          for (var i in options) {
            if (!(i in this.options)) {
              wmsParams[i] = options[i];
            }
          }
          options = setOptions(this, options);
          var realRetina = options.detectRetina && Browser.retina ? 2 : 1;
          var tileSize = this.getTileSize();
          wmsParams.width = tileSize.x * realRetina;
          wmsParams.height = tileSize.y * realRetina;
          this.wmsParams = wmsParams;
        },
        onAdd: function(map4) {
          this._crs = this.options.crs || map4.options.crs;
          this._wmsVersion = parseFloat(this.wmsParams.version);
          var projectionKey = this._wmsVersion >= 1.3 ? "crs" : "srs";
          this.wmsParams[projectionKey] = this._crs.code;
          TileLayer.prototype.onAdd.call(this, map4);
        },
        getTileUrl: function(coords) {
          var tileBounds = this._tileCoordsToNwSe(coords), crs = this._crs, bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])), min = bounds.min, max = bounds.max, bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ? [min.y, min.x, max.y, max.x] : [min.x, min.y, max.x, max.y]).join(","), url2 = TileLayer.prototype.getTileUrl.call(this, coords);
          return url2 + getParamString(this.wmsParams, url2, this.options.uppercase) + (this.options.uppercase ? "&BBOX=" : "&bbox=") + bbox;
        },
        // @method setParams(params: Object, noRedraw?: Boolean): this
        // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
        setParams: function(params, noRedraw) {
          extend3(this.wmsParams, params);
          if (!noRedraw) {
            this.redraw();
          }
          return this;
        }
      });
      function tileLayerWMS(url2, options) {
        return new TileLayerWMS(url2, options);
      }
      TileLayer.WMS = TileLayerWMS;
      tileLayer2.wms = tileLayerWMS;
      var Renderer = Layer.extend({
        // @section
        // @aka Renderer options
        options: {
          // @option padding: Number = 0.1
          // How much to extend the clip area around the map view (relative to its size)
          // e.g. 0.1 would be 10% of map view in each direction
          padding: 0.1
        },
        initialize: function(options) {
          setOptions(this, options);
          stamp(this);
          this._layers = this._layers || {};
        },
        onAdd: function() {
          if (!this._container) {
            this._initContainer();
            addClass(this._container, "leaflet-zoom-animated");
          }
          this.getPane().appendChild(this._container);
          this._update();
          this.on("update", this._updatePaths, this);
        },
        onRemove: function() {
          this.off("update", this._updatePaths, this);
          this._destroyContainer();
        },
        getEvents: function() {
          var events = {
            viewreset: this._reset,
            zoom: this._onZoom,
            moveend: this._update,
            zoomend: this._onZoomEnd
          };
          if (this._zoomAnimated) {
            events.zoomanim = this._onAnimZoom;
          }
          return events;
        },
        _onAnimZoom: function(ev) {
          this._updateTransform(ev.center, ev.zoom);
        },
        _onZoom: function() {
          this._updateTransform(this._map.getCenter(), this._map.getZoom());
        },
        _updateTransform: function(center2, zoom2) {
          var scale2 = this._map.getZoomScale(zoom2, this._zoom), viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding), currentCenterPoint = this._map.project(this._center, zoom2), topLeftOffset = viewHalf.multiplyBy(-scale2).add(currentCenterPoint).subtract(this._map._getNewPixelOrigin(center2, zoom2));
          if (Browser.any3d) {
            setTransform(this._container, topLeftOffset, scale2);
          } else {
            setPosition(this._container, topLeftOffset);
          }
        },
        _reset: function() {
          this._update();
          this._updateTransform(this._center, this._zoom);
          for (var id2 in this._layers) {
            this._layers[id2]._reset();
          }
        },
        _onZoomEnd: function() {
          for (var id2 in this._layers) {
            this._layers[id2]._project();
          }
        },
        _updatePaths: function() {
          for (var id2 in this._layers) {
            this._layers[id2]._update();
          }
        },
        _update: function() {
          var p = this.options.padding, size = this._map.getSize(), min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
          this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
          this._center = this._map.getCenter();
          this._zoom = this._map.getZoom();
        }
      });
      var Canvas = Renderer.extend({
        // @section
        // @aka Canvas options
        options: {
          // @option tolerance: Number = 0
          // How much to extend the click tolerance around a path/object on the map.
          tolerance: 0
        },
        getEvents: function() {
          var events = Renderer.prototype.getEvents.call(this);
          events.viewprereset = this._onViewPreReset;
          return events;
        },
        _onViewPreReset: function() {
          this._postponeUpdatePaths = true;
        },
        onAdd: function() {
          Renderer.prototype.onAdd.call(this);
          this._draw();
        },
        _initContainer: function() {
          var container = this._container = document.createElement("canvas");
          on(container, "mousemove", this._onMouseMove, this);
          on(container, "click dblclick mousedown mouseup contextmenu", this._onClick, this);
          on(container, "mouseout", this._handleMouseOut, this);
          container["_leaflet_disable_events"] = true;
          this._ctx = container.getContext("2d");
        },
        _destroyContainer: function() {
          cancelAnimFrame(this._redrawRequest);
          delete this._ctx;
          remove2(this._container);
          off(this._container);
          delete this._container;
        },
        _updatePaths: function() {
          if (this._postponeUpdatePaths) {
            return;
          }
          var layer;
          this._redrawBounds = null;
          for (var id2 in this._layers) {
            layer = this._layers[id2];
            layer._update();
          }
          this._redraw();
        },
        _update: function() {
          if (this._map._animatingZoom && this._bounds) {
            return;
          }
          Renderer.prototype._update.call(this);
          var b = this._bounds, container = this._container, size = b.getSize(), m = Browser.retina ? 2 : 1;
          setPosition(container, b.min);
          container.width = m * size.x;
          container.height = m * size.y;
          container.style.width = size.x + "px";
          container.style.height = size.y + "px";
          if (Browser.retina) {
            this._ctx.scale(2, 2);
          }
          this._ctx.translate(-b.min.x, -b.min.y);
          this.fire("update");
        },
        _reset: function() {
          Renderer.prototype._reset.call(this);
          if (this._postponeUpdatePaths) {
            this._postponeUpdatePaths = false;
            this._updatePaths();
          }
        },
        _initPath: function(layer) {
          this._updateDashArray(layer);
          this._layers[stamp(layer)] = layer;
          var order = layer._order = {
            layer,
            prev: this._drawLast,
            next: null
          };
          if (this._drawLast) {
            this._drawLast.next = order;
          }
          this._drawLast = order;
          this._drawFirst = this._drawFirst || this._drawLast;
        },
        _addPath: function(layer) {
          this._requestRedraw(layer);
        },
        _removePath: function(layer) {
          var order = layer._order;
          var next = order.next;
          var prev = order.prev;
          if (next) {
            next.prev = prev;
          } else {
            this._drawLast = prev;
          }
          if (prev) {
            prev.next = next;
          } else {
            this._drawFirst = next;
          }
          delete layer._order;
          delete this._layers[stamp(layer)];
          this._requestRedraw(layer);
        },
        _updatePath: function(layer) {
          this._extendRedrawBounds(layer);
          layer._project();
          layer._update();
          this._requestRedraw(layer);
        },
        _updateStyle: function(layer) {
          this._updateDashArray(layer);
          this._requestRedraw(layer);
        },
        _updateDashArray: function(layer) {
          if (typeof layer.options.dashArray === "string") {
            var parts = layer.options.dashArray.split(/[, ]+/), dashArray = [], dashValue, i;
            for (i = 0; i < parts.length; i++) {
              dashValue = Number(parts[i]);
              if (isNaN(dashValue)) {
                return;
              }
              dashArray.push(dashValue);
            }
            layer.options._dashArray = dashArray;
          } else {
            layer.options._dashArray = layer.options.dashArray;
          }
        },
        _requestRedraw: function(layer) {
          if (!this._map) {
            return;
          }
          this._extendRedrawBounds(layer);
          this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
        },
        _extendRedrawBounds: function(layer) {
          if (layer._pxBounds) {
            var padding = (layer.options.weight || 0) + 1;
            this._redrawBounds = this._redrawBounds || new Bounds();
            this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
            this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
          }
        },
        _redraw: function() {
          this._redrawRequest = null;
          if (this._redrawBounds) {
            this._redrawBounds.min._floor();
            this._redrawBounds.max._ceil();
          }
          this._clear();
          this._draw();
          this._redrawBounds = null;
        },
        _clear: function() {
          var bounds = this._redrawBounds;
          if (bounds) {
            var size = bounds.getSize();
            this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
          } else {
            this._ctx.save();
            this._ctx.setTransform(1, 0, 0, 1, 0, 0);
            this._ctx.clearRect(0, 0, this._container.width, this._container.height);
            this._ctx.restore();
          }
        },
        _draw: function() {
          var layer, bounds = this._redrawBounds;
          this._ctx.save();
          if (bounds) {
            var size = bounds.getSize();
            this._ctx.beginPath();
            this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
            this._ctx.clip();
          }
          this._drawing = true;
          for (var order = this._drawFirst; order; order = order.next) {
            layer = order.layer;
            if (!bounds || layer._pxBounds && layer._pxBounds.intersects(bounds)) {
              layer._updatePath();
            }
          }
          this._drawing = false;
          this._ctx.restore();
        },
        _updatePoly: function(layer, closed) {
          if (!this._drawing) {
            return;
          }
          var i, j, len2, p, parts = layer._parts, len = parts.length, ctx = this._ctx;
          if (!len) {
            return;
          }
          ctx.beginPath();
          for (i = 0; i < len; i++) {
            for (j = 0, len2 = parts[i].length; j < len2; j++) {
              p = parts[i][j];
              ctx[j ? "lineTo" : "moveTo"](p.x, p.y);
            }
            if (closed) {
              ctx.closePath();
            }
          }
          this._fillStroke(ctx, layer);
        },
        _updateCircle: function(layer) {
          if (!this._drawing || layer._empty()) {
            return;
          }
          var p = layer._point, ctx = this._ctx, r = Math.max(Math.round(layer._radius), 1), s2 = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
          if (s2 !== 1) {
            ctx.save();
            ctx.scale(1, s2);
          }
          ctx.beginPath();
          ctx.arc(p.x, p.y / s2, r, 0, Math.PI * 2, false);
          if (s2 !== 1) {
            ctx.restore();
          }
          this._fillStroke(ctx, layer);
        },
        _fillStroke: function(ctx, layer) {
          var options = layer.options;
          if (options.fill) {
            ctx.globalAlpha = options.fillOpacity;
            ctx.fillStyle = options.fillColor || options.color;
            ctx.fill(options.fillRule || "evenodd");
          }
          if (options.stroke && options.weight !== 0) {
            if (ctx.setLineDash) {
              ctx.setLineDash(layer.options && layer.options._dashArray || []);
            }
            ctx.globalAlpha = options.opacity;
            ctx.lineWidth = options.weight;
            ctx.strokeStyle = options.color;
            ctx.lineCap = options.lineCap;
            ctx.lineJoin = options.lineJoin;
            ctx.stroke();
          }
        },
        // Canvas obviously doesn't have mouse events for individual drawn objects,
        // so we emulate that by calculating what's under the mouse on mousemove/click manually
        _onClick: function(e) {
          var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
          for (var order = this._drawFirst; order; order = order.next) {
            layer = order.layer;
            if (layer.options.interactive && layer._containsPoint(point)) {
              if (!(e.type === "click" || e.type === "preclick") || !this._map._draggableMoved(layer)) {
                clickedLayer = layer;
              }
            }
          }
          this._fireEvent(clickedLayer ? [clickedLayer] : false, e);
        },
        _onMouseMove: function(e) {
          if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) {
            return;
          }
          var point = this._map.mouseEventToLayerPoint(e);
          this._handleMouseHover(e, point);
        },
        _handleMouseOut: function(e) {
          var layer = this._hoveredLayer;
          if (layer) {
            removeClass(this._container, "leaflet-interactive");
            this._fireEvent([layer], e, "mouseout");
            this._hoveredLayer = null;
            this._mouseHoverThrottled = false;
          }
        },
        _handleMouseHover: function(e, point) {
          if (this._mouseHoverThrottled) {
            return;
          }
          var layer, candidateHoveredLayer;
          for (var order = this._drawFirst; order; order = order.next) {
            layer = order.layer;
            if (layer.options.interactive && layer._containsPoint(point)) {
              candidateHoveredLayer = layer;
            }
          }
          if (candidateHoveredLayer !== this._hoveredLayer) {
            this._handleMouseOut(e);
            if (candidateHoveredLayer) {
              addClass(this._container, "leaflet-interactive");
              this._fireEvent([candidateHoveredLayer], e, "mouseover");
              this._hoveredLayer = candidateHoveredLayer;
            }
          }
          this._fireEvent(this._hoveredLayer ? [this._hoveredLayer] : false, e);
          this._mouseHoverThrottled = true;
          setTimeout(bind(function() {
            this._mouseHoverThrottled = false;
          }, this), 32);
        },
        _fireEvent: function(layers2, e, type) {
          this._map._fireDOMEvent(e, type || e.type, layers2);
        },
        _bringToFront: function(layer) {
          var order = layer._order;
          if (!order) {
            return;
          }
          var next = order.next;
          var prev = order.prev;
          if (next) {
            next.prev = prev;
          } else {
            return;
          }
          if (prev) {
            prev.next = next;
          } else if (next) {
            this._drawFirst = next;
          }
          order.prev = this._drawLast;
          this._drawLast.next = order;
          order.next = null;
          this._drawLast = order;
          this._requestRedraw(layer);
        },
        _bringToBack: function(layer) {
          var order = layer._order;
          if (!order) {
            return;
          }
          var next = order.next;
          var prev = order.prev;
          if (prev) {
            prev.next = next;
          } else {
            return;
          }
          if (next) {
            next.prev = prev;
          } else if (prev) {
            this._drawLast = prev;
          }
          order.prev = null;
          order.next = this._drawFirst;
          this._drawFirst.prev = order;
          this._drawFirst = order;
          this._requestRedraw(layer);
        }
      });
      function canvas(options) {
        return Browser.canvas ? new Canvas(options) : null;
      }
      var vmlCreate = (function() {
        try {
          document.namespaces.add("lvml", "urn:schemas-microsoft-com:vml");
          return function(name) {
            return document.createElement("<lvml:" + name + ' class="lvml">');
          };
        } catch (e) {
        }
        return function(name) {
          return document.createElement("<" + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
        };
      })();
      var vmlMixin = {
        _initContainer: function() {
          this._container = create$1("div", "leaflet-vml-container");
        },
        _update: function() {
          if (this._map._animatingZoom) {
            return;
          }
          Renderer.prototype._update.call(this);
          this.fire("update");
        },
        _initPath: function(layer) {
          var container = layer._container = vmlCreate("shape");
          addClass(container, "leaflet-vml-shape " + (this.options.className || ""));
          container.coordsize = "1 1";
          layer._path = vmlCreate("path");
          container.appendChild(layer._path);
          this._updateStyle(layer);
          this._layers[stamp(layer)] = layer;
        },
        _addPath: function(layer) {
          var container = layer._container;
          this._container.appendChild(container);
          if (layer.options.interactive) {
            layer.addInteractiveTarget(container);
          }
        },
        _removePath: function(layer) {
          var container = layer._container;
          remove2(container);
          layer.removeInteractiveTarget(container);
          delete this._layers[stamp(layer)];
        },
        _updateStyle: function(layer) {
          var stroke = layer._stroke, fill = layer._fill, options = layer.options, container = layer._container;
          container.stroked = !!options.stroke;
          container.filled = !!options.fill;
          if (options.stroke) {
            if (!stroke) {
              stroke = layer._stroke = vmlCreate("stroke");
            }
            container.appendChild(stroke);
            stroke.weight = options.weight + "px";
            stroke.color = options.color;
            stroke.opacity = options.opacity;
            if (options.dashArray) {
              stroke.dashStyle = isArray(options.dashArray) ? options.dashArray.join(" ") : options.dashArray.replace(/( *, *)/g, " ");
            } else {
              stroke.dashStyle = "";
            }
            stroke.endcap = options.lineCap.replace("butt", "flat");
            stroke.joinstyle = options.lineJoin;
          } else if (stroke) {
            container.removeChild(stroke);
            layer._stroke = null;
          }
          if (options.fill) {
            if (!fill) {
              fill = layer._fill = vmlCreate("fill");
            }
            container.appendChild(fill);
            fill.color = options.fillColor || options.color;
            fill.opacity = options.fillOpacity;
          } else if (fill) {
            container.removeChild(fill);
            layer._fill = null;
          }
        },
        _updateCircle: function(layer) {
          var p = layer._point.round(), r = Math.round(layer._radius), r2 = Math.round(layer._radiusY || r);
          this._setPath(layer, layer._empty() ? "M0 0" : "AL " + p.x + "," + p.y + " " + r + "," + r2 + " 0," + 65535 * 360);
        },
        _setPath: function(layer, path2) {
          layer._path.v = path2;
        },
        _bringToFront: function(layer) {
          toFront(layer._container);
        },
        _bringToBack: function(layer) {
          toBack(layer._container);
        }
      };
      var create2 = Browser.vml ? vmlCreate : svgCreate;
      var SVG = Renderer.extend({
        _initContainer: function() {
          this._container = create2("svg");
          this._container.setAttribute("pointer-events", "none");
          this._rootGroup = create2("g");
          this._container.appendChild(this._rootGroup);
        },
        _destroyContainer: function() {
          remove2(this._container);
          off(this._container);
          delete this._container;
          delete this._rootGroup;
          delete this._svgSize;
        },
        _update: function() {
          if (this._map._animatingZoom && this._bounds) {
            return;
          }
          Renderer.prototype._update.call(this);
          var b = this._bounds, size = b.getSize(), container = this._container;
          if (!this._svgSize || !this._svgSize.equals(size)) {
            this._svgSize = size;
            container.setAttribute("width", size.x);
            container.setAttribute("height", size.y);
          }
          setPosition(container, b.min);
          container.setAttribute("viewBox", [b.min.x, b.min.y, size.x, size.y].join(" "));
          this.fire("update");
        },
        // methods below are called by vector layers implementations
        _initPath: function(layer) {
          var path2 = layer._path = create2("path");
          if (layer.options.className) {
            addClass(path2, layer.options.className);
          }
          if (layer.options.interactive) {
            addClass(path2, "leaflet-interactive");
          }
          this._updateStyle(layer);
          this._layers[stamp(layer)] = layer;
        },
        _addPath: function(layer) {
          if (!this._rootGroup) {
            this._initContainer();
          }
          this._rootGroup.appendChild(layer._path);
          layer.addInteractiveTarget(layer._path);
        },
        _removePath: function(layer) {
          remove2(layer._path);
          layer.removeInteractiveTarget(layer._path);
          delete this._layers[stamp(layer)];
        },
        _updatePath: function(layer) {
          layer._project();
          layer._update();
        },
        _updateStyle: function(layer) {
          var path2 = layer._path, options = layer.options;
          if (!path2) {
            return;
          }
          if (options.stroke) {
            path2.setAttribute("stroke", options.color);
            path2.setAttribute("stroke-opacity", options.opacity);
            path2.setAttribute("stroke-width", options.weight);
            path2.setAttribute("stroke-linecap", options.lineCap);
            path2.setAttribute("stroke-linejoin", options.lineJoin);
            if (options.dashArray) {
              path2.setAttribute("stroke-dasharray", options.dashArray);
            } else {
              path2.removeAttribute("stroke-dasharray");
            }
            if (options.dashOffset) {
              path2.setAttribute("stroke-dashoffset", options.dashOffset);
            } else {
              path2.removeAttribute("stroke-dashoffset");
            }
          } else {
            path2.setAttribute("stroke", "none");
          }
          if (options.fill) {
            path2.setAttribute("fill", options.fillColor || options.color);
            path2.setAttribute("fill-opacity", options.fillOpacity);
            path2.setAttribute("fill-rule", options.fillRule || "evenodd");
          } else {
            path2.setAttribute("fill", "none");
          }
        },
        _updatePoly: function(layer, closed) {
          this._setPath(layer, pointsToPath(layer._parts, closed));
        },
        _updateCircle: function(layer) {
          var p = layer._point, r = Math.max(Math.round(layer._radius), 1), r2 = Math.max(Math.round(layer._radiusY), 1) || r, arc = "a" + r + "," + r2 + " 0 1,0 ";
          var d = layer._empty() ? "M0 0" : "M" + (p.x - r) + "," + p.y + arc + r * 2 + ",0 " + arc + -r * 2 + ",0 ";
          this._setPath(layer, d);
        },
        _setPath: function(layer, path2) {
          layer._path.setAttribute("d", path2);
        },
        // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
        _bringToFront: function(layer) {
          toFront(layer._path);
        },
        _bringToBack: function(layer) {
          toBack(layer._path);
        }
      });
      if (Browser.vml) {
        SVG.include(vmlMixin);
      }
      function svg(options) {
        return Browser.svg || Browser.vml ? new SVG(options) : null;
      }
      Map2.include({
        // @namespace Map; @method getRenderer(layer: Path): Renderer
        // Returns the instance of `Renderer` that should be used to render the given
        // `Path`. It will ensure that the `renderer` options of the map and paths
        // are respected, and that the renderers do exist on the map.
        getRenderer: function(layer) {
          var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
          if (!renderer) {
            renderer = this._renderer = this._createRenderer();
          }
          if (!this.hasLayer(renderer)) {
            this.addLayer(renderer);
          }
          return renderer;
        },
        _getPaneRenderer: function(name) {
          if (name === "overlayPane" || name === void 0) {
            return false;
          }
          var renderer = this._paneRenderers[name];
          if (renderer === void 0) {
            renderer = this._createRenderer({ pane: name });
            this._paneRenderers[name] = renderer;
          }
          return renderer;
        },
        _createRenderer: function(options) {
          return this.options.preferCanvas && canvas(options) || svg(options);
        }
      });
      var Rectangle = Polygon.extend({
        initialize: function(latLngBounds, options) {
          Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
        },
        // @method setBounds(latLngBounds: LatLngBounds): this
        // Redraws the rectangle with the passed bounds.
        setBounds: function(latLngBounds) {
          return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
        },
        _boundsToLatLngs: function(latLngBounds) {
          latLngBounds = toLatLngBounds(latLngBounds);
          return [
            latLngBounds.getSouthWest(),
            latLngBounds.getNorthWest(),
            latLngBounds.getNorthEast(),
            latLngBounds.getSouthEast()
          ];
        }
      });
      function rectangle2(latLngBounds, options) {
        return new Rectangle(latLngBounds, options);
      }
      SVG.create = create2;
      SVG.pointsToPath = pointsToPath;
      GeoJSON.geometryToLayer = geometryToLayer;
      GeoJSON.coordsToLatLng = coordsToLatLng;
      GeoJSON.coordsToLatLngs = coordsToLatLngs;
      GeoJSON.latLngToCoords = latLngToCoords;
      GeoJSON.latLngsToCoords = latLngsToCoords;
      GeoJSON.getFeature = getFeature;
      GeoJSON.asFeature = asFeature;
      Map2.mergeOptions({
        // @option boxZoom: Boolean = true
        // Whether the map can be zoomed to a rectangular area specified by
        // dragging the mouse while pressing the shift key.
        boxZoom: true
      });
      var BoxZoom = Handler.extend({
        initialize: function(map4) {
          this._map = map4;
          this._container = map4._container;
          this._pane = map4._panes.overlayPane;
          this._resetStateTimeout = 0;
          map4.on("unload", this._destroy, this);
        },
        addHooks: function() {
          on(this._container, "mousedown", this._onMouseDown, this);
        },
        removeHooks: function() {
          off(this._container, "mousedown", this._onMouseDown, this);
        },
        moved: function() {
          return this._moved;
        },
        _destroy: function() {
          remove2(this._pane);
          delete this._pane;
        },
        _resetState: function() {
          this._resetStateTimeout = 0;
          this._moved = false;
        },
        _clearDeferredResetState: function() {
          if (this._resetStateTimeout !== 0) {
            clearTimeout(this._resetStateTimeout);
            this._resetStateTimeout = 0;
          }
        },
        _onMouseDown: function(e) {
          if (!e.shiftKey || e.which !== 1 && e.button !== 1) {
            return false;
          }
          this._clearDeferredResetState();
          this._resetState();
          disableTextSelection();
          disableImageDrag();
          this._startPoint = this._map.mouseEventToContainerPoint(e);
          on(document, {
            contextmenu: stop,
            mousemove: this._onMouseMove,
            mouseup: this._onMouseUp,
            keydown: this._onKeyDown
          }, this);
        },
        _onMouseMove: function(e) {
          if (!this._moved) {
            this._moved = true;
            this._box = create$1("div", "leaflet-zoom-box", this._container);
            addClass(this._container, "leaflet-crosshair");
            this._map.fire("boxzoomstart");
          }
          this._point = this._map.mouseEventToContainerPoint(e);
          var bounds = new Bounds(this._point, this._startPoint), size = bounds.getSize();
          setPosition(this._box, bounds.min);
          this._box.style.width = size.x + "px";
          this._box.style.height = size.y + "px";
        },
        _finish: function() {
          if (this._moved) {
            remove2(this._box);
            removeClass(this._container, "leaflet-crosshair");
          }
          enableTextSelection();
          enableImageDrag();
          off(document, {
            contextmenu: stop,
            mousemove: this._onMouseMove,
            mouseup: this._onMouseUp,
            keydown: this._onKeyDown
          }, this);
        },
        _onMouseUp: function(e) {
          if (e.which !== 1 && e.button !== 1) {
            return;
          }
          this._finish();
          if (!this._moved) {
            return;
          }
          this._clearDeferredResetState();
          this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
          var bounds = new LatLngBounds(
            this._map.containerPointToLatLng(this._startPoint),
            this._map.containerPointToLatLng(this._point)
          );
          this._map.fitBounds(bounds).fire("boxzoomend", { boxZoomBounds: bounds });
        },
        _onKeyDown: function(e) {
          if (e.keyCode === 27) {
            this._finish();
            this._clearDeferredResetState();
            this._resetState();
          }
        }
      });
      Map2.addInitHook("addHandler", "boxZoom", BoxZoom);
      Map2.mergeOptions({
        // @option doubleClickZoom: Boolean|String = true
        // Whether the map can be zoomed in by double clicking on it and
        // zoomed out by double clicking while holding shift. If passed
        // `'center'`, double-click zoom will zoom to the center of the
        //  view regardless of where the mouse was.
        doubleClickZoom: true
      });
      var DoubleClickZoom = Handler.extend({
        addHooks: function() {
          this._map.on("dblclick", this._onDoubleClick, this);
        },
        removeHooks: function() {
          this._map.off("dblclick", this._onDoubleClick, this);
        },
        _onDoubleClick: function(e) {
          var map4 = this._map, oldZoom = map4.getZoom(), delta = map4.options.zoomDelta, zoom2 = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
          if (map4.options.doubleClickZoom === "center") {
            map4.setZoom(zoom2);
          } else {
            map4.setZoomAround(e.containerPoint, zoom2);
          }
        }
      });
      Map2.addInitHook("addHandler", "doubleClickZoom", DoubleClickZoom);
      Map2.mergeOptions({
        // @option dragging: Boolean = true
        // Whether the map is draggable with mouse/touch or not.
        dragging: true,
        // @section Panning Inertia Options
        // @option inertia: Boolean = *
        // If enabled, panning of the map will have an inertia effect where
        // the map builds momentum while dragging and continues moving in
        // the same direction for some time. Feels especially nice on touch
        // devices. Enabled by default.
        inertia: true,
        // @option inertiaDeceleration: Number = 3000
        // The rate with which the inertial movement slows down, in pixels/second².
        inertiaDeceleration: 3400,
        // px/s^2
        // @option inertiaMaxSpeed: Number = Infinity
        // Max speed of the inertial movement, in pixels/second.
        inertiaMaxSpeed: Infinity,
        // px/s
        // @option easeLinearity: Number = 0.2
        easeLinearity: 0.2,
        // TODO refactor, move to CRS
        // @option worldCopyJump: Boolean = false
        // With this option enabled, the map tracks when you pan to another "copy"
        // of the world and seamlessly jumps to the original one so that all overlays
        // like markers and vector layers are still visible.
        worldCopyJump: false,
        // @option maxBoundsViscosity: Number = 0.0
        // If `maxBounds` is set, this option will control how solid the bounds
        // are when dragging the map around. The default value of `0.0` allows the
        // user to drag outside the bounds at normal speed, higher values will
        // slow down map dragging outside bounds, and `1.0` makes the bounds fully
        // solid, preventing the user from dragging outside the bounds.
        maxBoundsViscosity: 0
      });
      var Drag = Handler.extend({
        addHooks: function() {
          if (!this._draggable) {
            var map4 = this._map;
            this._draggable = new Draggable(map4._mapPane, map4._container);
            this._draggable.on({
              dragstart: this._onDragStart,
              drag: this._onDrag,
              dragend: this._onDragEnd
            }, this);
            this._draggable.on("predrag", this._onPreDragLimit, this);
            if (map4.options.worldCopyJump) {
              this._draggable.on("predrag", this._onPreDragWrap, this);
              map4.on("zoomend", this._onZoomEnd, this);
              map4.whenReady(this._onZoomEnd, this);
            }
          }
          addClass(this._map._container, "leaflet-grab leaflet-touch-drag");
          this._draggable.enable();
          this._positions = [];
          this._times = [];
        },
        removeHooks: function() {
          removeClass(this._map._container, "leaflet-grab");
          removeClass(this._map._container, "leaflet-touch-drag");
          this._draggable.disable();
        },
        moved: function() {
          return this._draggable && this._draggable._moved;
        },
        moving: function() {
          return this._draggable && this._draggable._moving;
        },
        _onDragStart: function() {
          var map4 = this._map;
          map4._stop();
          if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
            var bounds = toLatLngBounds(this._map.options.maxBounds);
            this._offsetLimit = toBounds(
              this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
              this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1).add(this._map.getSize())
            );
            this._viscosity = Math.min(1, Math.max(0, this._map.options.maxBoundsViscosity));
          } else {
            this._offsetLimit = null;
          }
          map4.fire("movestart").fire("dragstart");
          if (map4.options.inertia) {
            this._positions = [];
            this._times = [];
          }
        },
        _onDrag: function(e) {
          if (this._map.options.inertia) {
            var time3 = this._lastTime = +/* @__PURE__ */ new Date(), pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
            this._positions.push(pos);
            this._times.push(time3);
            this._prunePositions(time3);
          }
          this._map.fire("move", e).fire("drag", e);
        },
        _prunePositions: function(time3) {
          while (this._positions.length > 1 && time3 - this._times[0] > 50) {
            this._positions.shift();
            this._times.shift();
          }
        },
        _onZoomEnd: function() {
          var pxCenter = this._map.getSize().divideBy(2), pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
          this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
          this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
        },
        _viscousLimit: function(value, threshold) {
          return value - (value - threshold) * this._viscosity;
        },
        _onPreDragLimit: function() {
          if (!this._viscosity || !this._offsetLimit) {
            return;
          }
          var offset2 = this._draggable._newPos.subtract(this._draggable._startPos);
          var limit = this._offsetLimit;
          if (offset2.x < limit.min.x) {
            offset2.x = this._viscousLimit(offset2.x, limit.min.x);
          }
          if (offset2.y < limit.min.y) {
            offset2.y = this._viscousLimit(offset2.y, limit.min.y);
          }
          if (offset2.x > limit.max.x) {
            offset2.x = this._viscousLimit(offset2.x, limit.max.x);
          }
          if (offset2.y > limit.max.y) {
            offset2.y = this._viscousLimit(offset2.y, limit.max.y);
          }
          this._draggable._newPos = this._draggable._startPos.add(offset2);
        },
        _onPreDragWrap: function() {
          var worldWidth = this._worldWidth, halfWidth = Math.round(worldWidth / 2), dx = this._initialWorldOffset, x2 = this._draggable._newPos.x, newX1 = (x2 - halfWidth + dx) % worldWidth + halfWidth - dx, newX2 = (x2 + halfWidth + dx) % worldWidth - halfWidth - dx, newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
          this._draggable._absPos = this._draggable._newPos.clone();
          this._draggable._newPos.x = newX;
        },
        _onDragEnd: function(e) {
          var map4 = this._map, options = map4.options, noInertia = !options.inertia || e.noInertia || this._times.length < 2;
          map4.fire("dragend", e);
          if (noInertia) {
            map4.fire("moveend");
          } else {
            this._prunePositions(+/* @__PURE__ */ new Date());
            var direction = this._lastPos.subtract(this._positions[0]), duration3 = (this._lastTime - this._times[0]) / 1e3, ease = options.easeLinearity, speedVector = direction.multiplyBy(ease / duration3), speed = speedVector.distanceTo([0, 0]), limitedSpeed = Math.min(options.inertiaMaxSpeed, speed), limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed), decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease), offset2 = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
            if (!offset2.x && !offset2.y) {
              map4.fire("moveend");
            } else {
              offset2 = map4._limitOffset(offset2, map4.options.maxBounds);
              requestAnimFrame(function() {
                map4.panBy(offset2, {
                  duration: decelerationDuration,
                  easeLinearity: ease,
                  noMoveStart: true,
                  animate: true
                });
              });
            }
          }
        }
      });
      Map2.addInitHook("addHandler", "dragging", Drag);
      Map2.mergeOptions({
        // @option keyboard: Boolean = true
        // Makes the map focusable and allows users to navigate the map with keyboard
        // arrows and `+`/`-` keys.
        keyboard: true,
        // @option keyboardPanDelta: Number = 80
        // Amount of pixels to pan when pressing an arrow key.
        keyboardPanDelta: 80
      });
      var Keyboard = Handler.extend({
        keyCodes: {
          left: [37],
          right: [39],
          down: [40],
          up: [38],
          zoomIn: [187, 107, 61, 171],
          zoomOut: [189, 109, 54, 173]
        },
        initialize: function(map4) {
          this._map = map4;
          this._setPanDelta(map4.options.keyboardPanDelta);
          this._setZoomDelta(map4.options.zoomDelta);
        },
        addHooks: function() {
          var container = this._map._container;
          if (container.tabIndex <= 0) {
            container.tabIndex = "0";
          }
          on(container, {
            focus: this._onFocus,
            blur: this._onBlur,
            mousedown: this._onMouseDown
          }, this);
          this._map.on({
            focus: this._addHooks,
            blur: this._removeHooks
          }, this);
        },
        removeHooks: function() {
          this._removeHooks();
          off(this._map._container, {
            focus: this._onFocus,
            blur: this._onBlur,
            mousedown: this._onMouseDown
          }, this);
          this._map.off({
            focus: this._addHooks,
            blur: this._removeHooks
          }, this);
        },
        _onMouseDown: function() {
          if (this._focused) {
            return;
          }
          var body = document.body, docEl = document.documentElement, top2 = body.scrollTop || docEl.scrollTop, left2 = body.scrollLeft || docEl.scrollLeft;
          this._map._container.focus();
          window.scrollTo(left2, top2);
        },
        _onFocus: function() {
          this._focused = true;
          this._map.fire("focus");
        },
        _onBlur: function() {
          this._focused = false;
          this._map.fire("blur");
        },
        _setPanDelta: function(panDelta) {
          var keys = this._panKeys = {}, codes = this.keyCodes, i, len;
          for (i = 0, len = codes.left.length; i < len; i++) {
            keys[codes.left[i]] = [-1 * panDelta, 0];
          }
          for (i = 0, len = codes.right.length; i < len; i++) {
            keys[codes.right[i]] = [panDelta, 0];
          }
          for (i = 0, len = codes.down.length; i < len; i++) {
            keys[codes.down[i]] = [0, panDelta];
          }
          for (i = 0, len = codes.up.length; i < len; i++) {
            keys[codes.up[i]] = [0, -1 * panDelta];
          }
        },
        _setZoomDelta: function(zoomDelta) {
          var keys = this._zoomKeys = {}, codes = this.keyCodes, i, len;
          for (i = 0, len = codes.zoomIn.length; i < len; i++) {
            keys[codes.zoomIn[i]] = zoomDelta;
          }
          for (i = 0, len = codes.zoomOut.length; i < len; i++) {
            keys[codes.zoomOut[i]] = -zoomDelta;
          }
        },
        _addHooks: function() {
          on(document, "keydown", this._onKeyDown, this);
        },
        _removeHooks: function() {
          off(document, "keydown", this._onKeyDown, this);
        },
        _onKeyDown: function(e) {
          if (e.altKey || e.ctrlKey || e.metaKey) {
            return;
          }
          var key = e.keyCode, map4 = this._map, offset2;
          if (key in this._panKeys) {
            if (!map4._panAnim || !map4._panAnim._inProgress) {
              offset2 = this._panKeys[key];
              if (e.shiftKey) {
                offset2 = toPoint(offset2).multiplyBy(3);
              }
              if (map4.options.maxBounds) {
                offset2 = map4._limitOffset(toPoint(offset2), map4.options.maxBounds);
              }
              if (map4.options.worldCopyJump) {
                var newLatLng = map4.wrapLatLng(map4.unproject(map4.project(map4.getCenter()).add(offset2)));
                map4.panTo(newLatLng);
              } else {
                map4.panBy(offset2);
              }
            }
          } else if (key in this._zoomKeys) {
            map4.setZoom(map4.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
          } else if (key === 27 && map4._popup && map4._popup.options.closeOnEscapeKey) {
            map4.closePopup();
          } else {
            return;
          }
          stop(e);
        }
      });
      Map2.addInitHook("addHandler", "keyboard", Keyboard);
      Map2.mergeOptions({
        // @section Mouse wheel options
        // @option scrollWheelZoom: Boolean|String = true
        // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
        // it will zoom to the center of the view regardless of where the mouse was.
        scrollWheelZoom: true,
        // @option wheelDebounceTime: Number = 40
        // Limits the rate at which a wheel can fire (in milliseconds). By default
        // user can't zoom via wheel more often than once per 40 ms.
        wheelDebounceTime: 40,
        // @option wheelPxPerZoomLevel: Number = 60
        // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
        // mean a change of one full zoom level. Smaller values will make wheel-zooming
        // faster (and vice versa).
        wheelPxPerZoomLevel: 60
      });
      var ScrollWheelZoom = Handler.extend({
        addHooks: function() {
          on(this._map._container, "wheel", this._onWheelScroll, this);
          this._delta = 0;
        },
        removeHooks: function() {
          off(this._map._container, "wheel", this._onWheelScroll, this);
        },
        _onWheelScroll: function(e) {
          var delta = getWheelDelta(e);
          var debounce = this._map.options.wheelDebounceTime;
          this._delta += delta;
          this._lastMousePos = this._map.mouseEventToContainerPoint(e);
          if (!this._startTime) {
            this._startTime = +/* @__PURE__ */ new Date();
          }
          var left2 = Math.max(debounce - (+/* @__PURE__ */ new Date() - this._startTime), 0);
          clearTimeout(this._timer);
          this._timer = setTimeout(bind(this._performZoom, this), left2);
          stop(e);
        },
        _performZoom: function() {
          var map4 = this._map, zoom2 = map4.getZoom(), snap = this._map.options.zoomSnap || 0;
          map4._stop();
          var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4), d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2, d4 = snap ? Math.ceil(d3 / snap) * snap : d3, delta = map4._limitZoom(zoom2 + (this._delta > 0 ? d4 : -d4)) - zoom2;
          this._delta = 0;
          this._startTime = null;
          if (!delta) {
            return;
          }
          if (map4.options.scrollWheelZoom === "center") {
            map4.setZoom(zoom2 + delta);
          } else {
            map4.setZoomAround(this._lastMousePos, zoom2 + delta);
          }
        }
      });
      Map2.addInitHook("addHandler", "scrollWheelZoom", ScrollWheelZoom);
      var tapHoldDelay = 600;
      Map2.mergeOptions({
        // @section Touch interaction options
        // @option tapHold: Boolean
        // Enables simulation of `contextmenu` event, default is `true` for mobile Safari.
        tapHold: Browser.touchNative && Browser.safari && Browser.mobile,
        // @option tapTolerance: Number = 15
        // The max number of pixels a user can shift his finger during touch
        // for it to be considered a valid tap.
        tapTolerance: 15
      });
      var TapHold = Handler.extend({
        addHooks: function() {
          on(this._map._container, "touchstart", this._onDown, this);
        },
        removeHooks: function() {
          off(this._map._container, "touchstart", this._onDown, this);
        },
        _onDown: function(e) {
          clearTimeout(this._holdTimeout);
          if (e.touches.length !== 1) {
            return;
          }
          var first = e.touches[0];
          this._startPos = this._newPos = new Point(first.clientX, first.clientY);
          this._holdTimeout = setTimeout(bind(function() {
            this._cancel();
            if (!this._isTapValid()) {
              return;
            }
            on(document, "touchend", preventDefault);
            on(document, "touchend touchcancel", this._cancelClickPrevent);
            this._simulateEvent("contextmenu", first);
          }, this), tapHoldDelay);
          on(document, "touchend touchcancel contextmenu", this._cancel, this);
          on(document, "touchmove", this._onMove, this);
        },
        _cancelClickPrevent: function cancelClickPrevent() {
          off(document, "touchend", preventDefault);
          off(document, "touchend touchcancel", cancelClickPrevent);
        },
        _cancel: function() {
          clearTimeout(this._holdTimeout);
          off(document, "touchend touchcancel contextmenu", this._cancel, this);
          off(document, "touchmove", this._onMove, this);
        },
        _onMove: function(e) {
          var first = e.touches[0];
          this._newPos = new Point(first.clientX, first.clientY);
        },
        _isTapValid: function() {
          return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
        },
        _simulateEvent: function(type, e) {
          var simulatedEvent = new MouseEvent(type, {
            bubbles: true,
            cancelable: true,
            view: window,
            // detail: 1,
            screenX: e.screenX,
            screenY: e.screenY,
            clientX: e.clientX,
            clientY: e.clientY
            // button: 2,
            // buttons: 2
          });
          simulatedEvent._simulated = true;
          e.target.dispatchEvent(simulatedEvent);
        }
      });
      Map2.addInitHook("addHandler", "tapHold", TapHold);
      Map2.mergeOptions({
        // @section Touch interaction options
        // @option touchZoom: Boolean|String = *
        // Whether the map can be zoomed by touch-dragging with two fingers. If
        // passed `'center'`, it will zoom to the center of the view regardless of
        // where the touch events (fingers) were. Enabled for touch-capable web
        // browsers.
        touchZoom: Browser.touch,
        // @option bounceAtZoomLimits: Boolean = true
        // Set it to false if you don't want the map to zoom beyond min/max zoom
        // and then bounce back when pinch-zooming.
        bounceAtZoomLimits: true
      });
      var TouchZoom = Handler.extend({
        addHooks: function() {
          addClass(this._map._container, "leaflet-touch-zoom");
          on(this._map._container, "touchstart", this._onTouchStart, this);
        },
        removeHooks: function() {
          removeClass(this._map._container, "leaflet-touch-zoom");
          off(this._map._container, "touchstart", this._onTouchStart, this);
        },
        _onTouchStart: function(e) {
          var map4 = this._map;
          if (!e.touches || e.touches.length !== 2 || map4._animatingZoom || this._zooming) {
            return;
          }
          var p1 = map4.mouseEventToContainerPoint(e.touches[0]), p2 = map4.mouseEventToContainerPoint(e.touches[1]);
          this._centerPoint = map4.getSize()._divideBy(2);
          this._startLatLng = map4.containerPointToLatLng(this._centerPoint);
          if (map4.options.touchZoom !== "center") {
            this._pinchStartLatLng = map4.containerPointToLatLng(p1.add(p2)._divideBy(2));
          }
          this._startDist = p1.distanceTo(p2);
          this._startZoom = map4.getZoom();
          this._moved = false;
          this._zooming = true;
          map4._stop();
          on(document, "touchmove", this._onTouchMove, this);
          on(document, "touchend touchcancel", this._onTouchEnd, this);
          preventDefault(e);
        },
        _onTouchMove: function(e) {
          if (!e.touches || e.touches.length !== 2 || !this._zooming) {
            return;
          }
          var map4 = this._map, p1 = map4.mouseEventToContainerPoint(e.touches[0]), p2 = map4.mouseEventToContainerPoint(e.touches[1]), scale2 = p1.distanceTo(p2) / this._startDist;
          this._zoom = map4.getScaleZoom(scale2, this._startZoom);
          if (!map4.options.bounceAtZoomLimits && (this._zoom < map4.getMinZoom() && scale2 < 1 || this._zoom > map4.getMaxZoom() && scale2 > 1)) {
            this._zoom = map4._limitZoom(this._zoom);
          }
          if (map4.options.touchZoom === "center") {
            this._center = this._startLatLng;
            if (scale2 === 1) {
              return;
            }
          } else {
            var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
            if (scale2 === 1 && delta.x === 0 && delta.y === 0) {
              return;
            }
            this._center = map4.unproject(map4.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
          }
          if (!this._moved) {
            map4._moveStart(true, false);
            this._moved = true;
          }
          cancelAnimFrame(this._animRequest);
          var moveFn = bind(map4._move, map4, this._center, this._zoom, { pinch: true, round: false }, void 0);
          this._animRequest = requestAnimFrame(moveFn, this, true);
          preventDefault(e);
        },
        _onTouchEnd: function() {
          if (!this._moved || !this._zooming) {
            this._zooming = false;
            return;
          }
          this._zooming = false;
          cancelAnimFrame(this._animRequest);
          off(document, "touchmove", this._onTouchMove, this);
          off(document, "touchend touchcancel", this._onTouchEnd, this);
          if (this._map.options.zoomAnimation) {
            this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
          } else {
            this._map._resetView(this._center, this._map._limitZoom(this._zoom));
          }
        }
      });
      Map2.addInitHook("addHandler", "touchZoom", TouchZoom);
      Map2.BoxZoom = BoxZoom;
      Map2.DoubleClickZoom = DoubleClickZoom;
      Map2.Drag = Drag;
      Map2.Keyboard = Keyboard;
      Map2.ScrollWheelZoom = ScrollWheelZoom;
      Map2.TapHold = TapHold;
      Map2.TouchZoom = TouchZoom;
      exports2.Bounds = Bounds;
      exports2.Browser = Browser;
      exports2.CRS = CRS;
      exports2.Canvas = Canvas;
      exports2.Circle = Circle;
      exports2.CircleMarker = CircleMarker;
      exports2.Class = Class2;
      exports2.Control = Control;
      exports2.DivIcon = DivIcon;
      exports2.DivOverlay = DivOverlay;
      exports2.DomEvent = DomEvent;
      exports2.DomUtil = DomUtil;
      exports2.Draggable = Draggable;
      exports2.Evented = Evented;
      exports2.FeatureGroup = FeatureGroup;
      exports2.GeoJSON = GeoJSON;
      exports2.GridLayer = GridLayer;
      exports2.Handler = Handler;
      exports2.Icon = Icon;
      exports2.ImageOverlay = ImageOverlay;
      exports2.LatLng = LatLng;
      exports2.LatLngBounds = LatLngBounds;
      exports2.Layer = Layer;
      exports2.LayerGroup = LayerGroup;
      exports2.LineUtil = LineUtil;
      exports2.Map = Map2;
      exports2.Marker = Marker;
      exports2.Mixin = Mixin;
      exports2.Path = Path2;
      exports2.Point = Point;
      exports2.PolyUtil = PolyUtil;
      exports2.Polygon = Polygon;
      exports2.Polyline = Polyline;
      exports2.Popup = Popup;
      exports2.PosAnimation = PosAnimation;
      exports2.Projection = index;
      exports2.Rectangle = Rectangle;
      exports2.Renderer = Renderer;
      exports2.SVG = SVG;
      exports2.SVGOverlay = SVGOverlay;
      exports2.TileLayer = TileLayer;
      exports2.Tooltip = Tooltip;
      exports2.Transformation = Transformation;
      exports2.Util = Util;
      exports2.VideoOverlay = VideoOverlay;
      exports2.bind = bind;
      exports2.bounds = toBounds;
      exports2.canvas = canvas;
      exports2.circle = circle2;
      exports2.circleMarker = circleMarker;
      exports2.control = control;
      exports2.divIcon = divIcon2;
      exports2.extend = extend3;
      exports2.featureGroup = featureGroup;
      exports2.geoJSON = geoJSON;
      exports2.geoJson = geoJson;
      exports2.gridLayer = gridLayer;
      exports2.icon = icon;
      exports2.imageOverlay = imageOverlay;
      exports2.latLng = toLatLng;
      exports2.latLngBounds = toLatLngBounds;
      exports2.layerGroup = layerGroup2;
      exports2.map = createMap;
      exports2.marker = marker2;
      exports2.point = toPoint;
      exports2.polygon = polygon;
      exports2.polyline = polyline;
      exports2.popup = popup;
      exports2.rectangle = rectangle2;
      exports2.setOptions = setOptions;
      exports2.stamp = stamp;
      exports2.svg = svg;
      exports2.svgOverlay = svgOverlay;
      exports2.tileLayer = tileLayer2;
      exports2.tooltip = tooltip;
      exports2.transformation = toTransformation;
      exports2.version = version3;
      exports2.videoOverlay = videoOverlay;
      var oldL = window.L;
      exports2.noConflict = function() {
        window.L = oldL;
        return this;
      };
      window.L = exports2;
    }));
  }
});

// node_modules/querystringify/index.js
var require_querystringify = __commonJS({
  "node_modules/querystringify/index.js"(exports) {
    "use strict";
    var has = Object.prototype.hasOwnProperty;
    var undef;
    function decode3(input) {
      try {
        return decodeURIComponent(input.replace(/\+/g, " "));
      } catch (e) {
        return null;
      }
    }
    function encode3(input) {
      try {
        return encodeURIComponent(input);
      } catch (e) {
        return null;
      }
    }
    function querystring(query) {
      var parser = /([^=?#&]+)=?([^&]*)/g, result = {}, part;
      while (part = parser.exec(query)) {
        var key = decode3(part[1]), value = decode3(part[2]);
        if (key === null || value === null || key in result) continue;
        result[key] = value;
      }
      return result;
    }
    function querystringify2(obj, prefix) {
      prefix = prefix || "";
      var pairs = [], value, key;
      if ("string" !== typeof prefix) prefix = "?";
      for (key in obj) {
        if (has.call(obj, key)) {
          value = obj[key];
          if (!value && (value === null || value === undef || isNaN(value))) {
            value = "";
          }
          key = encode3(key);
          value = encode3(value);
          if (key === null || value === null) continue;
          pairs.push(key + "=" + value);
        }
      }
      return pairs.length ? prefix + pairs.join("&") : "";
    }
    exports.stringify = querystringify2;
    exports.parse = querystring;
  }
});

// node_modules/jszip/dist/jszip.min.js
var require_jszip_min = __commonJS({
  "node_modules/jszip/dist/jszip.min.js"(exports, module) {
    !(function(e) {
      if ("object" == typeof exports && "undefined" != typeof module) module.exports = e();
      else if ("function" == typeof define && define.amd) define([], e);
      else {
        ("undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : this).JSZip = e();
      }
    })(function() {
      return (function s2(a, o, h) {
        function u(r, e3) {
          if (!o[r]) {
            if (!a[r]) {
              var t = "function" == typeof __require && __require;
              if (!e3 && t) return t(r, true);
              if (l2) return l2(r, true);
              var n2 = new Error("Cannot find module '" + r + "'");
              throw n2.code = "MODULE_NOT_FOUND", n2;
            }
            var i = o[r] = { exports: {} };
            a[r][0].call(i.exports, function(e4) {
              var t2 = a[r][1][e4];
              return u(t2 || e4);
            }, i, i.exports, s2, a, o, h);
          }
          return o[r].exports;
        }
        for (var l2 = "function" == typeof __require && __require, e = 0; e < h.length; e++) u(h[e]);
        return u;
      })({ 1: [function(e, t, r) {
        "use strict";
        var d = e("./utils"), c = e("./support"), p = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        r.encode = function(e3) {
          for (var t2, r2, n2, i, s2, a, o, h = [], u = 0, l2 = e3.length, f = l2, c2 = "string" !== d.getTypeOf(e3); u < e3.length; ) f = l2 - u, n2 = c2 ? (t2 = e3[u++], r2 = u < l2 ? e3[u++] : 0, u < l2 ? e3[u++] : 0) : (t2 = e3.charCodeAt(u++), r2 = u < l2 ? e3.charCodeAt(u++) : 0, u < l2 ? e3.charCodeAt(u++) : 0), i = t2 >> 2, s2 = (3 & t2) << 4 | r2 >> 4, a = 1 < f ? (15 & r2) << 2 | n2 >> 6 : 64, o = 2 < f ? 63 & n2 : 64, h.push(p.charAt(i) + p.charAt(s2) + p.charAt(a) + p.charAt(o));
          return h.join("");
        }, r.decode = function(e3) {
          var t2, r2, n2, i, s2, a, o = 0, h = 0, u = "data:";
          if (e3.substr(0, u.length) === u) throw new Error("Invalid base64 input, it looks like a data url.");
          var l2, f = 3 * (e3 = e3.replace(/[^A-Za-z0-9+/=]/g, "")).length / 4;
          if (e3.charAt(e3.length - 1) === p.charAt(64) && f--, e3.charAt(e3.length - 2) === p.charAt(64) && f--, f % 1 != 0) throw new Error("Invalid base64 input, bad content length.");
          for (l2 = c.uint8array ? new Uint8Array(0 | f) : new Array(0 | f); o < e3.length; ) t2 = p.indexOf(e3.charAt(o++)) << 2 | (i = p.indexOf(e3.charAt(o++))) >> 4, r2 = (15 & i) << 4 | (s2 = p.indexOf(e3.charAt(o++))) >> 2, n2 = (3 & s2) << 6 | (a = p.indexOf(e3.charAt(o++))), l2[h++] = t2, 64 !== s2 && (l2[h++] = r2), 64 !== a && (l2[h++] = n2);
          return l2;
        };
      }, { "./support": 30, "./utils": 32 }], 2: [function(e, t, r) {
        "use strict";
        var n2 = e("./external"), i = e("./stream/DataWorker"), s2 = e("./stream/Crc32Probe"), a = e("./stream/DataLengthProbe");
        function o(e3, t2, r2, n3, i2) {
          this.compressedSize = e3, this.uncompressedSize = t2, this.crc32 = r2, this.compression = n3, this.compressedContent = i2;
        }
        o.prototype = { getContentWorker: function() {
          var e3 = new i(n2.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a("data_length")), t2 = this;
          return e3.on("end", function() {
            if (this.streamInfo.data_length !== t2.uncompressedSize) throw new Error("Bug : uncompressed data size mismatch");
          }), e3;
        }, getCompressedWorker: function() {
          return new i(n2.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression);
        } }, o.createWorkerFrom = function(e3, t2, r2) {
          return e3.pipe(new s2()).pipe(new a("uncompressedSize")).pipe(t2.compressWorker(r2)).pipe(new a("compressedSize")).withStreamInfo("compression", t2);
        }, t.exports = o;
      }, { "./external": 6, "./stream/Crc32Probe": 25, "./stream/DataLengthProbe": 26, "./stream/DataWorker": 27 }], 3: [function(e, t, r) {
        "use strict";
        var n2 = e("./stream/GenericWorker");
        r.STORE = { magic: "\0\0", compressWorker: function() {
          return new n2("STORE compression");
        }, uncompressWorker: function() {
          return new n2("STORE decompression");
        } }, r.DEFLATE = e("./flate");
      }, { "./flate": 7, "./stream/GenericWorker": 28 }], 4: [function(e, t, r) {
        "use strict";
        var n2 = e("./utils");
        var o = (function() {
          for (var e3, t2 = [], r2 = 0; r2 < 256; r2++) {
            e3 = r2;
            for (var n3 = 0; n3 < 8; n3++) e3 = 1 & e3 ? 3988292384 ^ e3 >>> 1 : e3 >>> 1;
            t2[r2] = e3;
          }
          return t2;
        })();
        t.exports = function(e3, t2) {
          return void 0 !== e3 && e3.length ? "string" !== n2.getTypeOf(e3) ? (function(e4, t3, r2, n3) {
            var i = o, s2 = n3 + r2;
            e4 ^= -1;
            for (var a = n3; a < s2; a++) e4 = e4 >>> 8 ^ i[255 & (e4 ^ t3[a])];
            return -1 ^ e4;
          })(0 | t2, e3, e3.length, 0) : (function(e4, t3, r2, n3) {
            var i = o, s2 = n3 + r2;
            e4 ^= -1;
            for (var a = n3; a < s2; a++) e4 = e4 >>> 8 ^ i[255 & (e4 ^ t3.charCodeAt(a))];
            return -1 ^ e4;
          })(0 | t2, e3, e3.length, 0) : 0;
        };
      }, { "./utils": 32 }], 5: [function(e, t, r) {
        "use strict";
        r.base64 = false, r.binary = false, r.dir = false, r.createFolders = true, r.date = null, r.compression = null, r.compressionOptions = null, r.comment = null, r.unixPermissions = null, r.dosPermissions = null;
      }, {}], 6: [function(e, t, r) {
        "use strict";
        var n2 = null;
        n2 = "undefined" != typeof Promise ? Promise : e("lie"), t.exports = { Promise: n2 };
      }, { lie: 37 }], 7: [function(e, t, r) {
        "use strict";
        var n2 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Uint32Array, i = e("pako"), s2 = e("./utils"), a = e("./stream/GenericWorker"), o = n2 ? "uint8array" : "array";
        function h(e3, t2) {
          a.call(this, "FlateWorker/" + e3), this._pako = null, this._pakoAction = e3, this._pakoOptions = t2, this.meta = {};
        }
        r.magic = "\b\0", s2.inherits(h, a), h.prototype.processChunk = function(e3) {
          this.meta = e3.meta, null === this._pako && this._createPako(), this._pako.push(s2.transformTo(o, e3.data), false);
        }, h.prototype.flush = function() {
          a.prototype.flush.call(this), null === this._pako && this._createPako(), this._pako.push([], true);
        }, h.prototype.cleanUp = function() {
          a.prototype.cleanUp.call(this), this._pako = null;
        }, h.prototype._createPako = function() {
          this._pako = new i[this._pakoAction]({ raw: true, level: this._pakoOptions.level || -1 });
          var t2 = this;
          this._pako.onData = function(e3) {
            t2.push({ data: e3, meta: t2.meta });
          };
        }, r.compressWorker = function(e3) {
          return new h("Deflate", e3);
        }, r.uncompressWorker = function() {
          return new h("Inflate", {});
        };
      }, { "./stream/GenericWorker": 28, "./utils": 32, pako: 38 }], 8: [function(e, t, r) {
        "use strict";
        function A(e3, t2) {
          var r2, n3 = "";
          for (r2 = 0; r2 < t2; r2++) n3 += String.fromCharCode(255 & e3), e3 >>>= 8;
          return n3;
        }
        function n2(e3, t2, r2, n3, i2, s3) {
          var a, o, h = e3.file, u = e3.compression, l2 = s3 !== O.utf8encode, f = I.transformTo("string", s3(h.name)), c = I.transformTo("string", O.utf8encode(h.name)), d = h.comment, p = I.transformTo("string", s3(d)), m = I.transformTo("string", O.utf8encode(d)), _ = c.length !== h.name.length, g = m.length !== d.length, b = "", v = "", y2 = "", w = h.dir, k = h.date, x2 = { crc32: 0, compressedSize: 0, uncompressedSize: 0 };
          t2 && !r2 || (x2.crc32 = e3.crc32, x2.compressedSize = e3.compressedSize, x2.uncompressedSize = e3.uncompressedSize);
          var S = 0;
          t2 && (S |= 8), l2 || !_ && !g || (S |= 2048);
          var z2 = 0, C = 0;
          w && (z2 |= 16), "UNIX" === i2 ? (C = 798, z2 |= (function(e4, t3) {
            var r3 = e4;
            return e4 || (r3 = t3 ? 16893 : 33204), (65535 & r3) << 16;
          })(h.unixPermissions, w)) : (C = 20, z2 |= (function(e4) {
            return 63 & (e4 || 0);
          })(h.dosPermissions)), a = k.getUTCHours(), a <<= 6, a |= k.getUTCMinutes(), a <<= 5, a |= k.getUTCSeconds() / 2, o = k.getUTCFullYear() - 1980, o <<= 4, o |= k.getUTCMonth() + 1, o <<= 5, o |= k.getUTCDate(), _ && (v = A(1, 1) + A(B(f), 4) + c, b += "up" + A(v.length, 2) + v), g && (y2 = A(1, 1) + A(B(p), 4) + m, b += "uc" + A(y2.length, 2) + y2);
          var E = "";
          return E += "\n\0", E += A(S, 2), E += u.magic, E += A(a, 2), E += A(o, 2), E += A(x2.crc32, 4), E += A(x2.compressedSize, 4), E += A(x2.uncompressedSize, 4), E += A(f.length, 2), E += A(b.length, 2), { fileRecord: R.LOCAL_FILE_HEADER + E + f + b, dirRecord: R.CENTRAL_FILE_HEADER + A(C, 2) + E + A(p.length, 2) + "\0\0\0\0" + A(z2, 4) + A(n3, 4) + f + b + p };
        }
        var I = e("../utils"), i = e("../stream/GenericWorker"), O = e("../utf8"), B = e("../crc32"), R = e("../signature");
        function s2(e3, t2, r2, n3) {
          i.call(this, "ZipFileWorker"), this.bytesWritten = 0, this.zipComment = t2, this.zipPlatform = r2, this.encodeFileName = n3, this.streamFiles = e3, this.accumulate = false, this.contentBuffer = [], this.dirRecords = [], this.currentSourceOffset = 0, this.entriesCount = 0, this.currentFile = null, this._sources = [];
        }
        I.inherits(s2, i), s2.prototype.push = function(e3) {
          var t2 = e3.meta.percent || 0, r2 = this.entriesCount, n3 = this._sources.length;
          this.accumulate ? this.contentBuffer.push(e3) : (this.bytesWritten += e3.data.length, i.prototype.push.call(this, { data: e3.data, meta: { currentFile: this.currentFile, percent: r2 ? (t2 + 100 * (r2 - n3 - 1)) / r2 : 100 } }));
        }, s2.prototype.openedSource = function(e3) {
          this.currentSourceOffset = this.bytesWritten, this.currentFile = e3.file.name;
          var t2 = this.streamFiles && !e3.file.dir;
          if (t2) {
            var r2 = n2(e3, t2, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
            this.push({ data: r2.fileRecord, meta: { percent: 0 } });
          } else this.accumulate = true;
        }, s2.prototype.closedSource = function(e3) {
          this.accumulate = false;
          var t2 = this.streamFiles && !e3.file.dir, r2 = n2(e3, t2, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
          if (this.dirRecords.push(r2.dirRecord), t2) this.push({ data: (function(e4) {
            return R.DATA_DESCRIPTOR + A(e4.crc32, 4) + A(e4.compressedSize, 4) + A(e4.uncompressedSize, 4);
          })(e3), meta: { percent: 100 } });
          else for (this.push({ data: r2.fileRecord, meta: { percent: 0 } }); this.contentBuffer.length; ) this.push(this.contentBuffer.shift());
          this.currentFile = null;
        }, s2.prototype.flush = function() {
          for (var e3 = this.bytesWritten, t2 = 0; t2 < this.dirRecords.length; t2++) this.push({ data: this.dirRecords[t2], meta: { percent: 100 } });
          var r2 = this.bytesWritten - e3, n3 = (function(e4, t3, r3, n4, i2) {
            var s3 = I.transformTo("string", i2(n4));
            return R.CENTRAL_DIRECTORY_END + "\0\0\0\0" + A(e4, 2) + A(e4, 2) + A(t3, 4) + A(r3, 4) + A(s3.length, 2) + s3;
          })(this.dirRecords.length, r2, e3, this.zipComment, this.encodeFileName);
          this.push({ data: n3, meta: { percent: 100 } });
        }, s2.prototype.prepareNextSource = function() {
          this.previous = this._sources.shift(), this.openedSource(this.previous.streamInfo), this.isPaused ? this.previous.pause() : this.previous.resume();
        }, s2.prototype.registerPrevious = function(e3) {
          this._sources.push(e3);
          var t2 = this;
          return e3.on("data", function(e4) {
            t2.processChunk(e4);
          }), e3.on("end", function() {
            t2.closedSource(t2.previous.streamInfo), t2._sources.length ? t2.prepareNextSource() : t2.end();
          }), e3.on("error", function(e4) {
            t2.error(e4);
          }), this;
        }, s2.prototype.resume = function() {
          return !!i.prototype.resume.call(this) && (!this.previous && this._sources.length ? (this.prepareNextSource(), true) : this.previous || this._sources.length || this.generatedError ? void 0 : (this.end(), true));
        }, s2.prototype.error = function(e3) {
          var t2 = this._sources;
          if (!i.prototype.error.call(this, e3)) return false;
          for (var r2 = 0; r2 < t2.length; r2++) try {
            t2[r2].error(e3);
          } catch (e4) {
          }
          return true;
        }, s2.prototype.lock = function() {
          i.prototype.lock.call(this);
          for (var e3 = this._sources, t2 = 0; t2 < e3.length; t2++) e3[t2].lock();
        }, t.exports = s2;
      }, { "../crc32": 4, "../signature": 23, "../stream/GenericWorker": 28, "../utf8": 31, "../utils": 32 }], 9: [function(e, t, r) {
        "use strict";
        var u = e("../compressions"), n2 = e("./ZipFileWorker");
        r.generateWorker = function(e3, a, t2) {
          var o = new n2(a.streamFiles, t2, a.platform, a.encodeFileName), h = 0;
          try {
            e3.forEach(function(e4, t3) {
              h++;
              var r2 = (function(e6, t4) {
                var r3 = e6 || t4, n4 = u[r3];
                if (!n4) throw new Error(r3 + " is not a valid compression method !");
                return n4;
              })(t3.options.compression, a.compression), n3 = t3.options.compressionOptions || a.compressionOptions || {}, i = t3.dir, s2 = t3.date;
              t3._compressWorker(r2, n3).withStreamInfo("file", { name: e4, dir: i, date: s2, comment: t3.comment || "", unixPermissions: t3.unixPermissions, dosPermissions: t3.dosPermissions }).pipe(o);
            }), o.entriesCount = h;
          } catch (e4) {
            o.error(e4);
          }
          return o;
        };
      }, { "../compressions": 3, "./ZipFileWorker": 8 }], 10: [function(e, t, r) {
        "use strict";
        function n2() {
          if (!(this instanceof n2)) return new n2();
          if (arguments.length) throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
          this.files = /* @__PURE__ */ Object.create(null), this.comment = null, this.root = "", this.clone = function() {
            var e3 = new n2();
            for (var t2 in this) "function" != typeof this[t2] && (e3[t2] = this[t2]);
            return e3;
          };
        }
        (n2.prototype = e("./object")).loadAsync = e("./load"), n2.support = e("./support"), n2.defaults = e("./defaults"), n2.version = "3.10.1", n2.loadAsync = function(e3, t2) {
          return new n2().loadAsync(e3, t2);
        }, n2.external = e("./external"), t.exports = n2;
      }, { "./defaults": 5, "./external": 6, "./load": 11, "./object": 15, "./support": 30 }], 11: [function(e, t, r) {
        "use strict";
        var u = e("./utils"), i = e("./external"), n2 = e("./utf8"), s2 = e("./zipEntries"), a = e("./stream/Crc32Probe"), l2 = e("./nodejsUtils");
        function f(n3) {
          return new i.Promise(function(e3, t2) {
            var r2 = n3.decompressed.getContentWorker().pipe(new a());
            r2.on("error", function(e4) {
              t2(e4);
            }).on("end", function() {
              r2.streamInfo.crc32 !== n3.decompressed.crc32 ? t2(new Error("Corrupted zip : CRC32 mismatch")) : e3();
            }).resume();
          });
        }
        t.exports = function(e3, o) {
          var h = this;
          return o = u.extend(o || {}, { base64: false, checkCRC32: false, optimizedBinaryString: false, createFolders: false, decodeFileName: n2.utf8decode }), l2.isNode && l2.isStream(e3) ? i.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")) : u.prepareContent("the loaded zip file", e3, true, o.optimizedBinaryString, o.base64).then(function(e4) {
            var t2 = new s2(o);
            return t2.load(e4), t2;
          }).then(function(e4) {
            var t2 = [i.Promise.resolve(e4)], r2 = e4.files;
            if (o.checkCRC32) for (var n3 = 0; n3 < r2.length; n3++) t2.push(f(r2[n3]));
            return i.Promise.all(t2);
          }).then(function(e4) {
            for (var t2 = e4.shift(), r2 = t2.files, n3 = 0; n3 < r2.length; n3++) {
              var i2 = r2[n3], s3 = i2.fileNameStr, a2 = u.resolve(i2.fileNameStr);
              h.file(a2, i2.decompressed, { binary: true, optimizedBinaryString: true, date: i2.date, dir: i2.dir, comment: i2.fileCommentStr.length ? i2.fileCommentStr : null, unixPermissions: i2.unixPermissions, dosPermissions: i2.dosPermissions, createFolders: o.createFolders }), i2.dir || (h.file(a2).unsafeOriginalName = s3);
            }
            return t2.zipComment.length && (h.comment = t2.zipComment), h;
          });
        };
      }, { "./external": 6, "./nodejsUtils": 14, "./stream/Crc32Probe": 25, "./utf8": 31, "./utils": 32, "./zipEntries": 33 }], 12: [function(e, t, r) {
        "use strict";
        var n2 = e("../utils"), i = e("../stream/GenericWorker");
        function s2(e3, t2) {
          i.call(this, "Nodejs stream input adapter for " + e3), this._upstreamEnded = false, this._bindStream(t2);
        }
        n2.inherits(s2, i), s2.prototype._bindStream = function(e3) {
          var t2 = this;
          (this._stream = e3).pause(), e3.on("data", function(e4) {
            t2.push({ data: e4, meta: { percent: 0 } });
          }).on("error", function(e4) {
            t2.isPaused ? this.generatedError = e4 : t2.error(e4);
          }).on("end", function() {
            t2.isPaused ? t2._upstreamEnded = true : t2.end();
          });
        }, s2.prototype.pause = function() {
          return !!i.prototype.pause.call(this) && (this._stream.pause(), true);
        }, s2.prototype.resume = function() {
          return !!i.prototype.resume.call(this) && (this._upstreamEnded ? this.end() : this._stream.resume(), true);
        }, t.exports = s2;
      }, { "../stream/GenericWorker": 28, "../utils": 32 }], 13: [function(e, t, r) {
        "use strict";
        var i = e("readable-stream").Readable;
        function n2(e3, t2, r2) {
          i.call(this, t2), this._helper = e3;
          var n3 = this;
          e3.on("data", function(e4, t3) {
            n3.push(e4) || n3._helper.pause(), r2 && r2(t3);
          }).on("error", function(e4) {
            n3.emit("error", e4);
          }).on("end", function() {
            n3.push(null);
          });
        }
        e("../utils").inherits(n2, i), n2.prototype._read = function() {
          this._helper.resume();
        }, t.exports = n2;
      }, { "../utils": 32, "readable-stream": 16 }], 14: [function(e, t, r) {
        "use strict";
        t.exports = { isNode: "undefined" != typeof Buffer, newBufferFrom: function(e3, t2) {
          if (Buffer.from && Buffer.from !== Uint8Array.from) return Buffer.from(e3, t2);
          if ("number" == typeof e3) throw new Error('The "data" argument must not be a number');
          return new Buffer(e3, t2);
        }, allocBuffer: function(e3) {
          if (Buffer.alloc) return Buffer.alloc(e3);
          var t2 = new Buffer(e3);
          return t2.fill(0), t2;
        }, isBuffer: function(e3) {
          return Buffer.isBuffer(e3);
        }, isStream: function(e3) {
          return e3 && "function" == typeof e3.on && "function" == typeof e3.pause && "function" == typeof e3.resume;
        } };
      }, {}], 15: [function(e, t, r) {
        "use strict";
        function s2(e3, t2, r2) {
          var n3, i2 = u.getTypeOf(t2), s3 = u.extend(r2 || {}, f);
          s3.date = s3.date || /* @__PURE__ */ new Date(), null !== s3.compression && (s3.compression = s3.compression.toUpperCase()), "string" == typeof s3.unixPermissions && (s3.unixPermissions = parseInt(s3.unixPermissions, 8)), s3.unixPermissions && 16384 & s3.unixPermissions && (s3.dir = true), s3.dosPermissions && 16 & s3.dosPermissions && (s3.dir = true), s3.dir && (e3 = g(e3)), s3.createFolders && (n3 = _(e3)) && b.call(this, n3, true);
          var a2 = "string" === i2 && false === s3.binary && false === s3.base64;
          r2 && void 0 !== r2.binary || (s3.binary = !a2), (t2 instanceof c && 0 === t2.uncompressedSize || s3.dir || !t2 || 0 === t2.length) && (s3.base64 = false, s3.binary = true, t2 = "", s3.compression = "STORE", i2 = "string");
          var o2 = null;
          o2 = t2 instanceof c || t2 instanceof l2 ? t2 : p.isNode && p.isStream(t2) ? new m(e3, t2) : u.prepareContent(e3, t2, s3.binary, s3.optimizedBinaryString, s3.base64);
          var h2 = new d(e3, o2, s3);
          this.files[e3] = h2;
        }
        var i = e("./utf8"), u = e("./utils"), l2 = e("./stream/GenericWorker"), a = e("./stream/StreamHelper"), f = e("./defaults"), c = e("./compressedObject"), d = e("./zipObject"), o = e("./generate"), p = e("./nodejsUtils"), m = e("./nodejs/NodejsStreamInputAdapter"), _ = function(e3) {
          "/" === e3.slice(-1) && (e3 = e3.substring(0, e3.length - 1));
          var t2 = e3.lastIndexOf("/");
          return 0 < t2 ? e3.substring(0, t2) : "";
        }, g = function(e3) {
          return "/" !== e3.slice(-1) && (e3 += "/"), e3;
        }, b = function(e3, t2) {
          return t2 = void 0 !== t2 ? t2 : f.createFolders, e3 = g(e3), this.files[e3] || s2.call(this, e3, null, { dir: true, createFolders: t2 }), this.files[e3];
        };
        function h(e3) {
          return "[object RegExp]" === Object.prototype.toString.call(e3);
        }
        var n2 = { load: function() {
          throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
        }, forEach: function(e3) {
          var t2, r2, n3;
          for (t2 in this.files) n3 = this.files[t2], (r2 = t2.slice(this.root.length, t2.length)) && t2.slice(0, this.root.length) === this.root && e3(r2, n3);
        }, filter: function(r2) {
          var n3 = [];
          return this.forEach(function(e3, t2) {
            r2(e3, t2) && n3.push(t2);
          }), n3;
        }, file: function(e3, t2, r2) {
          if (1 !== arguments.length) return e3 = this.root + e3, s2.call(this, e3, t2, r2), this;
          if (h(e3)) {
            var n3 = e3;
            return this.filter(function(e4, t3) {
              return !t3.dir && n3.test(e4);
            });
          }
          var i2 = this.files[this.root + e3];
          return i2 && !i2.dir ? i2 : null;
        }, folder: function(r2) {
          if (!r2) return this;
          if (h(r2)) return this.filter(function(e4, t3) {
            return t3.dir && r2.test(e4);
          });
          var e3 = this.root + r2, t2 = b.call(this, e3), n3 = this.clone();
          return n3.root = t2.name, n3;
        }, remove: function(r2) {
          r2 = this.root + r2;
          var e3 = this.files[r2];
          if (e3 || ("/" !== r2.slice(-1) && (r2 += "/"), e3 = this.files[r2]), e3 && !e3.dir) delete this.files[r2];
          else for (var t2 = this.filter(function(e4, t3) {
            return t3.name.slice(0, r2.length) === r2;
          }), n3 = 0; n3 < t2.length; n3++) delete this.files[t2[n3].name];
          return this;
        }, generate: function() {
          throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
        }, generateInternalStream: function(e3) {
          var t2, r2 = {};
          try {
            if ((r2 = u.extend(e3 || {}, { streamFiles: false, compression: "STORE", compressionOptions: null, type: "", platform: "DOS", comment: null, mimeType: "application/zip", encodeFileName: i.utf8encode })).type = r2.type.toLowerCase(), r2.compression = r2.compression.toUpperCase(), "binarystring" === r2.type && (r2.type = "string"), !r2.type) throw new Error("No output type specified.");
            u.checkSupport(r2.type), "darwin" !== r2.platform && "freebsd" !== r2.platform && "linux" !== r2.platform && "sunos" !== r2.platform || (r2.platform = "UNIX"), "win32" === r2.platform && (r2.platform = "DOS");
            var n3 = r2.comment || this.comment || "";
            t2 = o.generateWorker(this, r2, n3);
          } catch (e4) {
            (t2 = new l2("error")).error(e4);
          }
          return new a(t2, r2.type || "string", r2.mimeType);
        }, generateAsync: function(e3, t2) {
          return this.generateInternalStream(e3).accumulate(t2);
        }, generateNodeStream: function(e3, t2) {
          return (e3 = e3 || {}).type || (e3.type = "nodebuffer"), this.generateInternalStream(e3).toNodejsStream(t2);
        } };
        t.exports = n2;
      }, { "./compressedObject": 2, "./defaults": 5, "./generate": 9, "./nodejs/NodejsStreamInputAdapter": 12, "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31, "./utils": 32, "./zipObject": 35 }], 16: [function(e, t, r) {
        "use strict";
        t.exports = e("stream");
      }, { stream: void 0 }], 17: [function(e, t, r) {
        "use strict";
        var n2 = e("./DataReader");
        function i(e3) {
          n2.call(this, e3);
          for (var t2 = 0; t2 < this.data.length; t2++) e3[t2] = 255 & e3[t2];
        }
        e("../utils").inherits(i, n2), i.prototype.byteAt = function(e3) {
          return this.data[this.zero + e3];
        }, i.prototype.lastIndexOfSignature = function(e3) {
          for (var t2 = e3.charCodeAt(0), r2 = e3.charCodeAt(1), n3 = e3.charCodeAt(2), i2 = e3.charCodeAt(3), s2 = this.length - 4; 0 <= s2; --s2) if (this.data[s2] === t2 && this.data[s2 + 1] === r2 && this.data[s2 + 2] === n3 && this.data[s2 + 3] === i2) return s2 - this.zero;
          return -1;
        }, i.prototype.readAndCheckSignature = function(e3) {
          var t2 = e3.charCodeAt(0), r2 = e3.charCodeAt(1), n3 = e3.charCodeAt(2), i2 = e3.charCodeAt(3), s2 = this.readData(4);
          return t2 === s2[0] && r2 === s2[1] && n3 === s2[2] && i2 === s2[3];
        }, i.prototype.readData = function(e3) {
          if (this.checkOffset(e3), 0 === e3) return [];
          var t2 = this.data.slice(this.zero + this.index, this.zero + this.index + e3);
          return this.index += e3, t2;
        }, t.exports = i;
      }, { "../utils": 32, "./DataReader": 18 }], 18: [function(e, t, r) {
        "use strict";
        var n2 = e("../utils");
        function i(e3) {
          this.data = e3, this.length = e3.length, this.index = 0, this.zero = 0;
        }
        i.prototype = { checkOffset: function(e3) {
          this.checkIndex(this.index + e3);
        }, checkIndex: function(e3) {
          if (this.length < this.zero + e3 || e3 < 0) throw new Error("End of data reached (data length = " + this.length + ", asked index = " + e3 + "). Corrupted zip ?");
        }, setIndex: function(e3) {
          this.checkIndex(e3), this.index = e3;
        }, skip: function(e3) {
          this.setIndex(this.index + e3);
        }, byteAt: function() {
        }, readInt: function(e3) {
          var t2, r2 = 0;
          for (this.checkOffset(e3), t2 = this.index + e3 - 1; t2 >= this.index; t2--) r2 = (r2 << 8) + this.byteAt(t2);
          return this.index += e3, r2;
        }, readString: function(e3) {
          return n2.transformTo("string", this.readData(e3));
        }, readData: function() {
        }, lastIndexOfSignature: function() {
        }, readAndCheckSignature: function() {
        }, readDate: function() {
          var e3 = this.readInt(4);
          return new Date(Date.UTC(1980 + (e3 >> 25 & 127), (e3 >> 21 & 15) - 1, e3 >> 16 & 31, e3 >> 11 & 31, e3 >> 5 & 63, (31 & e3) << 1));
        } }, t.exports = i;
      }, { "../utils": 32 }], 19: [function(e, t, r) {
        "use strict";
        var n2 = e("./Uint8ArrayReader");
        function i(e3) {
          n2.call(this, e3);
        }
        e("../utils").inherits(i, n2), i.prototype.readData = function(e3) {
          this.checkOffset(e3);
          var t2 = this.data.slice(this.zero + this.index, this.zero + this.index + e3);
          return this.index += e3, t2;
        }, t.exports = i;
      }, { "../utils": 32, "./Uint8ArrayReader": 21 }], 20: [function(e, t, r) {
        "use strict";
        var n2 = e("./DataReader");
        function i(e3) {
          n2.call(this, e3);
        }
        e("../utils").inherits(i, n2), i.prototype.byteAt = function(e3) {
          return this.data.charCodeAt(this.zero + e3);
        }, i.prototype.lastIndexOfSignature = function(e3) {
          return this.data.lastIndexOf(e3) - this.zero;
        }, i.prototype.readAndCheckSignature = function(e3) {
          return e3 === this.readData(4);
        }, i.prototype.readData = function(e3) {
          this.checkOffset(e3);
          var t2 = this.data.slice(this.zero + this.index, this.zero + this.index + e3);
          return this.index += e3, t2;
        }, t.exports = i;
      }, { "../utils": 32, "./DataReader": 18 }], 21: [function(e, t, r) {
        "use strict";
        var n2 = e("./ArrayReader");
        function i(e3) {
          n2.call(this, e3);
        }
        e("../utils").inherits(i, n2), i.prototype.readData = function(e3) {
          if (this.checkOffset(e3), 0 === e3) return new Uint8Array(0);
          var t2 = this.data.subarray(this.zero + this.index, this.zero + this.index + e3);
          return this.index += e3, t2;
        }, t.exports = i;
      }, { "../utils": 32, "./ArrayReader": 17 }], 22: [function(e, t, r) {
        "use strict";
        var n2 = e("../utils"), i = e("../support"), s2 = e("./ArrayReader"), a = e("./StringReader"), o = e("./NodeBufferReader"), h = e("./Uint8ArrayReader");
        t.exports = function(e3) {
          var t2 = n2.getTypeOf(e3);
          return n2.checkSupport(t2), "string" !== t2 || i.uint8array ? "nodebuffer" === t2 ? new o(e3) : i.uint8array ? new h(n2.transformTo("uint8array", e3)) : new s2(n2.transformTo("array", e3)) : new a(e3);
        };
      }, { "../support": 30, "../utils": 32, "./ArrayReader": 17, "./NodeBufferReader": 19, "./StringReader": 20, "./Uint8ArrayReader": 21 }], 23: [function(e, t, r) {
        "use strict";
        r.LOCAL_FILE_HEADER = "PK", r.CENTRAL_FILE_HEADER = "PK", r.CENTRAL_DIRECTORY_END = "PK", r.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x07", r.ZIP64_CENTRAL_DIRECTORY_END = "PK", r.DATA_DESCRIPTOR = "PK\x07\b";
      }, {}], 24: [function(e, t, r) {
        "use strict";
        var n2 = e("./GenericWorker"), i = e("../utils");
        function s2(e3) {
          n2.call(this, "ConvertWorker to " + e3), this.destType = e3;
        }
        i.inherits(s2, n2), s2.prototype.processChunk = function(e3) {
          this.push({ data: i.transformTo(this.destType, e3.data), meta: e3.meta });
        }, t.exports = s2;
      }, { "../utils": 32, "./GenericWorker": 28 }], 25: [function(e, t, r) {
        "use strict";
        var n2 = e("./GenericWorker"), i = e("../crc32");
        function s2() {
          n2.call(this, "Crc32Probe"), this.withStreamInfo("crc32", 0);
        }
        e("../utils").inherits(s2, n2), s2.prototype.processChunk = function(e3) {
          this.streamInfo.crc32 = i(e3.data, this.streamInfo.crc32 || 0), this.push(e3);
        }, t.exports = s2;
      }, { "../crc32": 4, "../utils": 32, "./GenericWorker": 28 }], 26: [function(e, t, r) {
        "use strict";
        var n2 = e("../utils"), i = e("./GenericWorker");
        function s2(e3) {
          i.call(this, "DataLengthProbe for " + e3), this.propName = e3, this.withStreamInfo(e3, 0);
        }
        n2.inherits(s2, i), s2.prototype.processChunk = function(e3) {
          if (e3) {
            var t2 = this.streamInfo[this.propName] || 0;
            this.streamInfo[this.propName] = t2 + e3.data.length;
          }
          i.prototype.processChunk.call(this, e3);
        }, t.exports = s2;
      }, { "../utils": 32, "./GenericWorker": 28 }], 27: [function(e, t, r) {
        "use strict";
        var n2 = e("../utils"), i = e("./GenericWorker");
        function s2(e3) {
          i.call(this, "DataWorker");
          var t2 = this;
          this.dataIsReady = false, this.index = 0, this.max = 0, this.data = null, this.type = "", this._tickScheduled = false, e3.then(function(e4) {
            t2.dataIsReady = true, t2.data = e4, t2.max = e4 && e4.length || 0, t2.type = n2.getTypeOf(e4), t2.isPaused || t2._tickAndRepeat();
          }, function(e4) {
            t2.error(e4);
          });
        }
        n2.inherits(s2, i), s2.prototype.cleanUp = function() {
          i.prototype.cleanUp.call(this), this.data = null;
        }, s2.prototype.resume = function() {
          return !!i.prototype.resume.call(this) && (!this._tickScheduled && this.dataIsReady && (this._tickScheduled = true, n2.delay(this._tickAndRepeat, [], this)), true);
        }, s2.prototype._tickAndRepeat = function() {
          this._tickScheduled = false, this.isPaused || this.isFinished || (this._tick(), this.isFinished || (n2.delay(this._tickAndRepeat, [], this), this._tickScheduled = true));
        }, s2.prototype._tick = function() {
          if (this.isPaused || this.isFinished) return false;
          var e3 = null, t2 = Math.min(this.max, this.index + 16384);
          if (this.index >= this.max) return this.end();
          switch (this.type) {
            case "string":
              e3 = this.data.substring(this.index, t2);
              break;
            case "uint8array":
              e3 = this.data.subarray(this.index, t2);
              break;
            case "array":
            case "nodebuffer":
              e3 = this.data.slice(this.index, t2);
          }
          return this.index = t2, this.push({ data: e3, meta: { percent: this.max ? this.index / this.max * 100 : 0 } });
        }, t.exports = s2;
      }, { "../utils": 32, "./GenericWorker": 28 }], 28: [function(e, t, r) {
        "use strict";
        function n2(e3) {
          this.name = e3 || "default", this.streamInfo = {}, this.generatedError = null, this.extraStreamInfo = {}, this.isPaused = true, this.isFinished = false, this.isLocked = false, this._listeners = { data: [], end: [], error: [] }, this.previous = null;
        }
        n2.prototype = { push: function(e3) {
          this.emit("data", e3);
        }, end: function() {
          if (this.isFinished) return false;
          this.flush();
          try {
            this.emit("end"), this.cleanUp(), this.isFinished = true;
          } catch (e3) {
            this.emit("error", e3);
          }
          return true;
        }, error: function(e3) {
          return !this.isFinished && (this.isPaused ? this.generatedError = e3 : (this.isFinished = true, this.emit("error", e3), this.previous && this.previous.error(e3), this.cleanUp()), true);
        }, on: function(e3, t2) {
          return this._listeners[e3].push(t2), this;
        }, cleanUp: function() {
          this.streamInfo = this.generatedError = this.extraStreamInfo = null, this._listeners = [];
        }, emit: function(e3, t2) {
          if (this._listeners[e3]) for (var r2 = 0; r2 < this._listeners[e3].length; r2++) this._listeners[e3][r2].call(this, t2);
        }, pipe: function(e3) {
          return e3.registerPrevious(this);
        }, registerPrevious: function(e3) {
          if (this.isLocked) throw new Error("The stream '" + this + "' has already been used.");
          this.streamInfo = e3.streamInfo, this.mergeStreamInfo(), this.previous = e3;
          var t2 = this;
          return e3.on("data", function(e4) {
            t2.processChunk(e4);
          }), e3.on("end", function() {
            t2.end();
          }), e3.on("error", function(e4) {
            t2.error(e4);
          }), this;
        }, pause: function() {
          return !this.isPaused && !this.isFinished && (this.isPaused = true, this.previous && this.previous.pause(), true);
        }, resume: function() {
          if (!this.isPaused || this.isFinished) return false;
          var e3 = this.isPaused = false;
          return this.generatedError && (this.error(this.generatedError), e3 = true), this.previous && this.previous.resume(), !e3;
        }, flush: function() {
        }, processChunk: function(e3) {
          this.push(e3);
        }, withStreamInfo: function(e3, t2) {
          return this.extraStreamInfo[e3] = t2, this.mergeStreamInfo(), this;
        }, mergeStreamInfo: function() {
          for (var e3 in this.extraStreamInfo) Object.prototype.hasOwnProperty.call(this.extraStreamInfo, e3) && (this.streamInfo[e3] = this.extraStreamInfo[e3]);
        }, lock: function() {
          if (this.isLocked) throw new Error("The stream '" + this + "' has already been used.");
          this.isLocked = true, this.previous && this.previous.lock();
        }, toString: function() {
          var e3 = "Worker " + this.name;
          return this.previous ? this.previous + " -> " + e3 : e3;
        } }, t.exports = n2;
      }, {}], 29: [function(e, t, r) {
        "use strict";
        var h = e("../utils"), i = e("./ConvertWorker"), s2 = e("./GenericWorker"), u = e("../base64"), n2 = e("../support"), a = e("../external"), o = null;
        if (n2.nodestream) try {
          o = e("../nodejs/NodejsStreamOutputAdapter");
        } catch (e3) {
        }
        function l2(e3, o2) {
          return new a.Promise(function(t2, r2) {
            var n3 = [], i2 = e3._internalType, s3 = e3._outputType, a2 = e3._mimeType;
            e3.on("data", function(e4, t3) {
              n3.push(e4), o2 && o2(t3);
            }).on("error", function(e4) {
              n3 = [], r2(e4);
            }).on("end", function() {
              try {
                var e4 = (function(e6, t3, r3) {
                  switch (e6) {
                    case "blob":
                      return h.newBlob(h.transformTo("arraybuffer", t3), r3);
                    case "base64":
                      return u.encode(t3);
                    default:
                      return h.transformTo(e6, t3);
                  }
                })(s3, (function(e6, t3) {
                  var r3, n4 = 0, i3 = null, s4 = 0;
                  for (r3 = 0; r3 < t3.length; r3++) s4 += t3[r3].length;
                  switch (e6) {
                    case "string":
                      return t3.join("");
                    case "array":
                      return Array.prototype.concat.apply([], t3);
                    case "uint8array":
                      for (i3 = new Uint8Array(s4), r3 = 0; r3 < t3.length; r3++) i3.set(t3[r3], n4), n4 += t3[r3].length;
                      return i3;
                    case "nodebuffer":
                      return Buffer.concat(t3);
                    default:
                      throw new Error("concat : unsupported type '" + e6 + "'");
                  }
                })(i2, n3), a2);
                t2(e4);
              } catch (e6) {
                r2(e6);
              }
              n3 = [];
            }).resume();
          });
        }
        function f(e3, t2, r2) {
          var n3 = t2;
          switch (t2) {
            case "blob":
            case "arraybuffer":
              n3 = "uint8array";
              break;
            case "base64":
              n3 = "string";
          }
          try {
            this._internalType = n3, this._outputType = t2, this._mimeType = r2, h.checkSupport(n3), this._worker = e3.pipe(new i(n3)), e3.lock();
          } catch (e4) {
            this._worker = new s2("error"), this._worker.error(e4);
          }
        }
        f.prototype = { accumulate: function(e3) {
          return l2(this, e3);
        }, on: function(e3, t2) {
          var r2 = this;
          return "data" === e3 ? this._worker.on(e3, function(e4) {
            t2.call(r2, e4.data, e4.meta);
          }) : this._worker.on(e3, function() {
            h.delay(t2, arguments, r2);
          }), this;
        }, resume: function() {
          return h.delay(this._worker.resume, [], this._worker), this;
        }, pause: function() {
          return this._worker.pause(), this;
        }, toNodejsStream: function(e3) {
          if (h.checkSupport("nodestream"), "nodebuffer" !== this._outputType) throw new Error(this._outputType + " is not supported by this method");
          return new o(this, { objectMode: "nodebuffer" !== this._outputType }, e3);
        } }, t.exports = f;
      }, { "../base64": 1, "../external": 6, "../nodejs/NodejsStreamOutputAdapter": 13, "../support": 30, "../utils": 32, "./ConvertWorker": 24, "./GenericWorker": 28 }], 30: [function(e, t, r) {
        "use strict";
        if (r.base64 = true, r.array = true, r.string = true, r.arraybuffer = "undefined" != typeof ArrayBuffer && "undefined" != typeof Uint8Array, r.nodebuffer = "undefined" != typeof Buffer, r.uint8array = "undefined" != typeof Uint8Array, "undefined" == typeof ArrayBuffer) r.blob = false;
        else {
          var n2 = new ArrayBuffer(0);
          try {
            r.blob = 0 === new Blob([n2], { type: "application/zip" }).size;
          } catch (e3) {
            try {
              var i = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)();
              i.append(n2), r.blob = 0 === i.getBlob("application/zip").size;
            } catch (e4) {
              r.blob = false;
            }
          }
        }
        try {
          r.nodestream = !!e("readable-stream").Readable;
        } catch (e3) {
          r.nodestream = false;
        }
      }, { "readable-stream": 16 }], 31: [function(e, t, s2) {
        "use strict";
        for (var o = e("./utils"), h = e("./support"), r = e("./nodejsUtils"), n2 = e("./stream/GenericWorker"), u = new Array(256), i = 0; i < 256; i++) u[i] = 252 <= i ? 6 : 248 <= i ? 5 : 240 <= i ? 4 : 224 <= i ? 3 : 192 <= i ? 2 : 1;
        u[254] = u[254] = 1;
        function a() {
          n2.call(this, "utf-8 decode"), this.leftOver = null;
        }
        function l2() {
          n2.call(this, "utf-8 encode");
        }
        s2.utf8encode = function(e3) {
          return h.nodebuffer ? r.newBufferFrom(e3, "utf-8") : (function(e4) {
            var t2, r2, n3, i2, s3, a2 = e4.length, o2 = 0;
            for (i2 = 0; i2 < a2; i2++) 55296 == (64512 & (r2 = e4.charCodeAt(i2))) && i2 + 1 < a2 && 56320 == (64512 & (n3 = e4.charCodeAt(i2 + 1))) && (r2 = 65536 + (r2 - 55296 << 10) + (n3 - 56320), i2++), o2 += r2 < 128 ? 1 : r2 < 2048 ? 2 : r2 < 65536 ? 3 : 4;
            for (t2 = h.uint8array ? new Uint8Array(o2) : new Array(o2), i2 = s3 = 0; s3 < o2; i2++) 55296 == (64512 & (r2 = e4.charCodeAt(i2))) && i2 + 1 < a2 && 56320 == (64512 & (n3 = e4.charCodeAt(i2 + 1))) && (r2 = 65536 + (r2 - 55296 << 10) + (n3 - 56320), i2++), r2 < 128 ? t2[s3++] = r2 : (r2 < 2048 ? t2[s3++] = 192 | r2 >>> 6 : (r2 < 65536 ? t2[s3++] = 224 | r2 >>> 12 : (t2[s3++] = 240 | r2 >>> 18, t2[s3++] = 128 | r2 >>> 12 & 63), t2[s3++] = 128 | r2 >>> 6 & 63), t2[s3++] = 128 | 63 & r2);
            return t2;
          })(e3);
        }, s2.utf8decode = function(e3) {
          return h.nodebuffer ? o.transformTo("nodebuffer", e3).toString("utf-8") : (function(e4) {
            var t2, r2, n3, i2, s3 = e4.length, a2 = new Array(2 * s3);
            for (t2 = r2 = 0; t2 < s3; ) if ((n3 = e4[t2++]) < 128) a2[r2++] = n3;
            else if (4 < (i2 = u[n3])) a2[r2++] = 65533, t2 += i2 - 1;
            else {
              for (n3 &= 2 === i2 ? 31 : 3 === i2 ? 15 : 7; 1 < i2 && t2 < s3; ) n3 = n3 << 6 | 63 & e4[t2++], i2--;
              1 < i2 ? a2[r2++] = 65533 : n3 < 65536 ? a2[r2++] = n3 : (n3 -= 65536, a2[r2++] = 55296 | n3 >> 10 & 1023, a2[r2++] = 56320 | 1023 & n3);
            }
            return a2.length !== r2 && (a2.subarray ? a2 = a2.subarray(0, r2) : a2.length = r2), o.applyFromCharCode(a2);
          })(e3 = o.transformTo(h.uint8array ? "uint8array" : "array", e3));
        }, o.inherits(a, n2), a.prototype.processChunk = function(e3) {
          var t2 = o.transformTo(h.uint8array ? "uint8array" : "array", e3.data);
          if (this.leftOver && this.leftOver.length) {
            if (h.uint8array) {
              var r2 = t2;
              (t2 = new Uint8Array(r2.length + this.leftOver.length)).set(this.leftOver, 0), t2.set(r2, this.leftOver.length);
            } else t2 = this.leftOver.concat(t2);
            this.leftOver = null;
          }
          var n3 = (function(e4, t3) {
            var r3;
            for ((t3 = t3 || e4.length) > e4.length && (t3 = e4.length), r3 = t3 - 1; 0 <= r3 && 128 == (192 & e4[r3]); ) r3--;
            return r3 < 0 ? t3 : 0 === r3 ? t3 : r3 + u[e4[r3]] > t3 ? r3 : t3;
          })(t2), i2 = t2;
          n3 !== t2.length && (h.uint8array ? (i2 = t2.subarray(0, n3), this.leftOver = t2.subarray(n3, t2.length)) : (i2 = t2.slice(0, n3), this.leftOver = t2.slice(n3, t2.length))), this.push({ data: s2.utf8decode(i2), meta: e3.meta });
        }, a.prototype.flush = function() {
          this.leftOver && this.leftOver.length && (this.push({ data: s2.utf8decode(this.leftOver), meta: {} }), this.leftOver = null);
        }, s2.Utf8DecodeWorker = a, o.inherits(l2, n2), l2.prototype.processChunk = function(e3) {
          this.push({ data: s2.utf8encode(e3.data), meta: e3.meta });
        }, s2.Utf8EncodeWorker = l2;
      }, { "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./support": 30, "./utils": 32 }], 32: [function(e, t, a) {
        "use strict";
        var o = e("./support"), h = e("./base64"), r = e("./nodejsUtils"), u = e("./external");
        function n2(e3) {
          return e3;
        }
        function l2(e3, t2) {
          for (var r2 = 0; r2 < e3.length; ++r2) t2[r2] = 255 & e3.charCodeAt(r2);
          return t2;
        }
        e("setimmediate"), a.newBlob = function(t2, r2) {
          a.checkSupport("blob");
          try {
            return new Blob([t2], { type: r2 });
          } catch (e3) {
            try {
              var n3 = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)();
              return n3.append(t2), n3.getBlob(r2);
            } catch (e4) {
              throw new Error("Bug : can't construct the Blob.");
            }
          }
        };
        var i = { stringifyByChunk: function(e3, t2, r2) {
          var n3 = [], i2 = 0, s3 = e3.length;
          if (s3 <= r2) return String.fromCharCode.apply(null, e3);
          for (; i2 < s3; ) "array" === t2 || "nodebuffer" === t2 ? n3.push(String.fromCharCode.apply(null, e3.slice(i2, Math.min(i2 + r2, s3)))) : n3.push(String.fromCharCode.apply(null, e3.subarray(i2, Math.min(i2 + r2, s3)))), i2 += r2;
          return n3.join("");
        }, stringifyByChar: function(e3) {
          for (var t2 = "", r2 = 0; r2 < e3.length; r2++) t2 += String.fromCharCode(e3[r2]);
          return t2;
        }, applyCanBeUsed: { uint8array: (function() {
          try {
            return o.uint8array && 1 === String.fromCharCode.apply(null, new Uint8Array(1)).length;
          } catch (e3) {
            return false;
          }
        })(), nodebuffer: (function() {
          try {
            return o.nodebuffer && 1 === String.fromCharCode.apply(null, r.allocBuffer(1)).length;
          } catch (e3) {
            return false;
          }
        })() } };
        function s2(e3) {
          var t2 = 65536, r2 = a.getTypeOf(e3), n3 = true;
          if ("uint8array" === r2 ? n3 = i.applyCanBeUsed.uint8array : "nodebuffer" === r2 && (n3 = i.applyCanBeUsed.nodebuffer), n3) for (; 1 < t2; ) try {
            return i.stringifyByChunk(e3, r2, t2);
          } catch (e4) {
            t2 = Math.floor(t2 / 2);
          }
          return i.stringifyByChar(e3);
        }
        function f(e3, t2) {
          for (var r2 = 0; r2 < e3.length; r2++) t2[r2] = e3[r2];
          return t2;
        }
        a.applyFromCharCode = s2;
        var c = {};
        c.string = { string: n2, array: function(e3) {
          return l2(e3, new Array(e3.length));
        }, arraybuffer: function(e3) {
          return c.string.uint8array(e3).buffer;
        }, uint8array: function(e3) {
          return l2(e3, new Uint8Array(e3.length));
        }, nodebuffer: function(e3) {
          return l2(e3, r.allocBuffer(e3.length));
        } }, c.array = { string: s2, array: n2, arraybuffer: function(e3) {
          return new Uint8Array(e3).buffer;
        }, uint8array: function(e3) {
          return new Uint8Array(e3);
        }, nodebuffer: function(e3) {
          return r.newBufferFrom(e3);
        } }, c.arraybuffer = { string: function(e3) {
          return s2(new Uint8Array(e3));
        }, array: function(e3) {
          return f(new Uint8Array(e3), new Array(e3.byteLength));
        }, arraybuffer: n2, uint8array: function(e3) {
          return new Uint8Array(e3);
        }, nodebuffer: function(e3) {
          return r.newBufferFrom(new Uint8Array(e3));
        } }, c.uint8array = { string: s2, array: function(e3) {
          return f(e3, new Array(e3.length));
        }, arraybuffer: function(e3) {
          return e3.buffer;
        }, uint8array: n2, nodebuffer: function(e3) {
          return r.newBufferFrom(e3);
        } }, c.nodebuffer = { string: s2, array: function(e3) {
          return f(e3, new Array(e3.length));
        }, arraybuffer: function(e3) {
          return c.nodebuffer.uint8array(e3).buffer;
        }, uint8array: function(e3) {
          return f(e3, new Uint8Array(e3.length));
        }, nodebuffer: n2 }, a.transformTo = function(e3, t2) {
          if (t2 = t2 || "", !e3) return t2;
          a.checkSupport(e3);
          var r2 = a.getTypeOf(t2);
          return c[r2][e3](t2);
        }, a.resolve = function(e3) {
          for (var t2 = e3.split("/"), r2 = [], n3 = 0; n3 < t2.length; n3++) {
            var i2 = t2[n3];
            "." === i2 || "" === i2 && 0 !== n3 && n3 !== t2.length - 1 || (".." === i2 ? r2.pop() : r2.push(i2));
          }
          return r2.join("/");
        }, a.getTypeOf = function(e3) {
          return "string" == typeof e3 ? "string" : "[object Array]" === Object.prototype.toString.call(e3) ? "array" : o.nodebuffer && r.isBuffer(e3) ? "nodebuffer" : o.uint8array && e3 instanceof Uint8Array ? "uint8array" : o.arraybuffer && e3 instanceof ArrayBuffer ? "arraybuffer" : void 0;
        }, a.checkSupport = function(e3) {
          if (!o[e3.toLowerCase()]) throw new Error(e3 + " is not supported by this platform");
        }, a.MAX_VALUE_16BITS = 65535, a.MAX_VALUE_32BITS = -1, a.pretty = function(e3) {
          var t2, r2, n3 = "";
          for (r2 = 0; r2 < (e3 || "").length; r2++) n3 += "\\x" + ((t2 = e3.charCodeAt(r2)) < 16 ? "0" : "") + t2.toString(16).toUpperCase();
          return n3;
        }, a.delay = function(e3, t2, r2) {
          setImmediate(function() {
            e3.apply(r2 || null, t2 || []);
          });
        }, a.inherits = function(e3, t2) {
          function r2() {
          }
          r2.prototype = t2.prototype, e3.prototype = new r2();
        }, a.extend = function() {
          var e3, t2, r2 = {};
          for (e3 = 0; e3 < arguments.length; e3++) for (t2 in arguments[e3]) Object.prototype.hasOwnProperty.call(arguments[e3], t2) && void 0 === r2[t2] && (r2[t2] = arguments[e3][t2]);
          return r2;
        }, a.prepareContent = function(r2, e3, n3, i2, s3) {
          return u.Promise.resolve(e3).then(function(n4) {
            return o.blob && (n4 instanceof Blob || -1 !== ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(n4))) && "undefined" != typeof FileReader ? new u.Promise(function(t2, r3) {
              var e4 = new FileReader();
              e4.onload = function(e6) {
                t2(e6.target.result);
              }, e4.onerror = function(e6) {
                r3(e6.target.error);
              }, e4.readAsArrayBuffer(n4);
            }) : n4;
          }).then(function(e4) {
            var t2 = a.getTypeOf(e4);
            return t2 ? ("arraybuffer" === t2 ? e4 = a.transformTo("uint8array", e4) : "string" === t2 && (s3 ? e4 = h.decode(e4) : n3 && true !== i2 && (e4 = (function(e6) {
              return l2(e6, o.uint8array ? new Uint8Array(e6.length) : new Array(e6.length));
            })(e4))), e4) : u.Promise.reject(new Error("Can't read the data of '" + r2 + "'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"));
          });
        };
      }, { "./base64": 1, "./external": 6, "./nodejsUtils": 14, "./support": 30, setimmediate: 54 }], 33: [function(e, t, r) {
        "use strict";
        var n2 = e("./reader/readerFor"), i = e("./utils"), s2 = e("./signature"), a = e("./zipEntry"), o = e("./support");
        function h(e3) {
          this.files = [], this.loadOptions = e3;
        }
        h.prototype = { checkSignature: function(e3) {
          if (!this.reader.readAndCheckSignature(e3)) {
            this.reader.index -= 4;
            var t2 = this.reader.readString(4);
            throw new Error("Corrupted zip or bug: unexpected signature (" + i.pretty(t2) + ", expected " + i.pretty(e3) + ")");
          }
        }, isSignature: function(e3, t2) {
          var r2 = this.reader.index;
          this.reader.setIndex(e3);
          var n3 = this.reader.readString(4) === t2;
          return this.reader.setIndex(r2), n3;
        }, readBlockEndOfCentral: function() {
          this.diskNumber = this.reader.readInt(2), this.diskWithCentralDirStart = this.reader.readInt(2), this.centralDirRecordsOnThisDisk = this.reader.readInt(2), this.centralDirRecords = this.reader.readInt(2), this.centralDirSize = this.reader.readInt(4), this.centralDirOffset = this.reader.readInt(4), this.zipCommentLength = this.reader.readInt(2);
          var e3 = this.reader.readData(this.zipCommentLength), t2 = o.uint8array ? "uint8array" : "array", r2 = i.transformTo(t2, e3);
          this.zipComment = this.loadOptions.decodeFileName(r2);
        }, readBlockZip64EndOfCentral: function() {
          this.zip64EndOfCentralSize = this.reader.readInt(8), this.reader.skip(4), this.diskNumber = this.reader.readInt(4), this.diskWithCentralDirStart = this.reader.readInt(4), this.centralDirRecordsOnThisDisk = this.reader.readInt(8), this.centralDirRecords = this.reader.readInt(8), this.centralDirSize = this.reader.readInt(8), this.centralDirOffset = this.reader.readInt(8), this.zip64ExtensibleData = {};
          for (var e3, t2, r2, n3 = this.zip64EndOfCentralSize - 44; 0 < n3; ) e3 = this.reader.readInt(2), t2 = this.reader.readInt(4), r2 = this.reader.readData(t2), this.zip64ExtensibleData[e3] = { id: e3, length: t2, value: r2 };
        }, readBlockZip64EndOfCentralLocator: function() {
          if (this.diskWithZip64CentralDirStart = this.reader.readInt(4), this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8), this.disksCount = this.reader.readInt(4), 1 < this.disksCount) throw new Error("Multi-volumes zip are not supported");
        }, readLocalFiles: function() {
          var e3, t2;
          for (e3 = 0; e3 < this.files.length; e3++) t2 = this.files[e3], this.reader.setIndex(t2.localHeaderOffset), this.checkSignature(s2.LOCAL_FILE_HEADER), t2.readLocalPart(this.reader), t2.handleUTF8(), t2.processAttributes();
        }, readCentralDir: function() {
          var e3;
          for (this.reader.setIndex(this.centralDirOffset); this.reader.readAndCheckSignature(s2.CENTRAL_FILE_HEADER); ) (e3 = new a({ zip64: this.zip64 }, this.loadOptions)).readCentralPart(this.reader), this.files.push(e3);
          if (this.centralDirRecords !== this.files.length && 0 !== this.centralDirRecords && 0 === this.files.length) throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
        }, readEndOfCentral: function() {
          var e3 = this.reader.lastIndexOfSignature(s2.CENTRAL_DIRECTORY_END);
          if (e3 < 0) throw !this.isSignature(0, s2.LOCAL_FILE_HEADER) ? new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html") : new Error("Corrupted zip: can't find end of central directory");
          this.reader.setIndex(e3);
          var t2 = e3;
          if (this.checkSignature(s2.CENTRAL_DIRECTORY_END), this.readBlockEndOfCentral(), this.diskNumber === i.MAX_VALUE_16BITS || this.diskWithCentralDirStart === i.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === i.MAX_VALUE_16BITS || this.centralDirRecords === i.MAX_VALUE_16BITS || this.centralDirSize === i.MAX_VALUE_32BITS || this.centralDirOffset === i.MAX_VALUE_32BITS) {
            if (this.zip64 = true, (e3 = this.reader.lastIndexOfSignature(s2.ZIP64_CENTRAL_DIRECTORY_LOCATOR)) < 0) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
            if (this.reader.setIndex(e3), this.checkSignature(s2.ZIP64_CENTRAL_DIRECTORY_LOCATOR), this.readBlockZip64EndOfCentralLocator(), !this.isSignature(this.relativeOffsetEndOfZip64CentralDir, s2.ZIP64_CENTRAL_DIRECTORY_END) && (this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(s2.ZIP64_CENTRAL_DIRECTORY_END), this.relativeOffsetEndOfZip64CentralDir < 0)) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
            this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir), this.checkSignature(s2.ZIP64_CENTRAL_DIRECTORY_END), this.readBlockZip64EndOfCentral();
          }
          var r2 = this.centralDirOffset + this.centralDirSize;
          this.zip64 && (r2 += 20, r2 += 12 + this.zip64EndOfCentralSize);
          var n3 = t2 - r2;
          if (0 < n3) this.isSignature(t2, s2.CENTRAL_FILE_HEADER) || (this.reader.zero = n3);
          else if (n3 < 0) throw new Error("Corrupted zip: missing " + Math.abs(n3) + " bytes.");
        }, prepareReader: function(e3) {
          this.reader = n2(e3);
        }, load: function(e3) {
          this.prepareReader(e3), this.readEndOfCentral(), this.readCentralDir(), this.readLocalFiles();
        } }, t.exports = h;
      }, { "./reader/readerFor": 22, "./signature": 23, "./support": 30, "./utils": 32, "./zipEntry": 34 }], 34: [function(e, t, r) {
        "use strict";
        var n2 = e("./reader/readerFor"), s2 = e("./utils"), i = e("./compressedObject"), a = e("./crc32"), o = e("./utf8"), h = e("./compressions"), u = e("./support");
        function l2(e3, t2) {
          this.options = e3, this.loadOptions = t2;
        }
        l2.prototype = { isEncrypted: function() {
          return 1 == (1 & this.bitFlag);
        }, useUTF8: function() {
          return 2048 == (2048 & this.bitFlag);
        }, readLocalPart: function(e3) {
          var t2, r2;
          if (e3.skip(22), this.fileNameLength = e3.readInt(2), r2 = e3.readInt(2), this.fileName = e3.readData(this.fileNameLength), e3.skip(r2), -1 === this.compressedSize || -1 === this.uncompressedSize) throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");
          if (null === (t2 = (function(e4) {
            for (var t3 in h) if (Object.prototype.hasOwnProperty.call(h, t3) && h[t3].magic === e4) return h[t3];
            return null;
          })(this.compressionMethod))) throw new Error("Corrupted zip : compression " + s2.pretty(this.compressionMethod) + " unknown (inner file : " + s2.transformTo("string", this.fileName) + ")");
          this.decompressed = new i(this.compressedSize, this.uncompressedSize, this.crc32, t2, e3.readData(this.compressedSize));
        }, readCentralPart: function(e3) {
          this.versionMadeBy = e3.readInt(2), e3.skip(2), this.bitFlag = e3.readInt(2), this.compressionMethod = e3.readString(2), this.date = e3.readDate(), this.crc32 = e3.readInt(4), this.compressedSize = e3.readInt(4), this.uncompressedSize = e3.readInt(4);
          var t2 = e3.readInt(2);
          if (this.extraFieldsLength = e3.readInt(2), this.fileCommentLength = e3.readInt(2), this.diskNumberStart = e3.readInt(2), this.internalFileAttributes = e3.readInt(2), this.externalFileAttributes = e3.readInt(4), this.localHeaderOffset = e3.readInt(4), this.isEncrypted()) throw new Error("Encrypted zip are not supported");
          e3.skip(t2), this.readExtraFields(e3), this.parseZIP64ExtraField(e3), this.fileComment = e3.readData(this.fileCommentLength);
        }, processAttributes: function() {
          this.unixPermissions = null, this.dosPermissions = null;
          var e3 = this.versionMadeBy >> 8;
          this.dir = !!(16 & this.externalFileAttributes), 0 == e3 && (this.dosPermissions = 63 & this.externalFileAttributes), 3 == e3 && (this.unixPermissions = this.externalFileAttributes >> 16 & 65535), this.dir || "/" !== this.fileNameStr.slice(-1) || (this.dir = true);
        }, parseZIP64ExtraField: function() {
          if (this.extraFields[1]) {
            var e3 = n2(this.extraFields[1].value);
            this.uncompressedSize === s2.MAX_VALUE_32BITS && (this.uncompressedSize = e3.readInt(8)), this.compressedSize === s2.MAX_VALUE_32BITS && (this.compressedSize = e3.readInt(8)), this.localHeaderOffset === s2.MAX_VALUE_32BITS && (this.localHeaderOffset = e3.readInt(8)), this.diskNumberStart === s2.MAX_VALUE_32BITS && (this.diskNumberStart = e3.readInt(4));
          }
        }, readExtraFields: function(e3) {
          var t2, r2, n3, i2 = e3.index + this.extraFieldsLength;
          for (this.extraFields || (this.extraFields = {}); e3.index + 4 < i2; ) t2 = e3.readInt(2), r2 = e3.readInt(2), n3 = e3.readData(r2), this.extraFields[t2] = { id: t2, length: r2, value: n3 };
          e3.setIndex(i2);
        }, handleUTF8: function() {
          var e3 = u.uint8array ? "uint8array" : "array";
          if (this.useUTF8()) this.fileNameStr = o.utf8decode(this.fileName), this.fileCommentStr = o.utf8decode(this.fileComment);
          else {
            var t2 = this.findExtraFieldUnicodePath();
            if (null !== t2) this.fileNameStr = t2;
            else {
              var r2 = s2.transformTo(e3, this.fileName);
              this.fileNameStr = this.loadOptions.decodeFileName(r2);
            }
            var n3 = this.findExtraFieldUnicodeComment();
            if (null !== n3) this.fileCommentStr = n3;
            else {
              var i2 = s2.transformTo(e3, this.fileComment);
              this.fileCommentStr = this.loadOptions.decodeFileName(i2);
            }
          }
        }, findExtraFieldUnicodePath: function() {
          var e3 = this.extraFields[28789];
          if (e3) {
            var t2 = n2(e3.value);
            return 1 !== t2.readInt(1) ? null : a(this.fileName) !== t2.readInt(4) ? null : o.utf8decode(t2.readData(e3.length - 5));
          }
          return null;
        }, findExtraFieldUnicodeComment: function() {
          var e3 = this.extraFields[25461];
          if (e3) {
            var t2 = n2(e3.value);
            return 1 !== t2.readInt(1) ? null : a(this.fileComment) !== t2.readInt(4) ? null : o.utf8decode(t2.readData(e3.length - 5));
          }
          return null;
        } }, t.exports = l2;
      }, { "./compressedObject": 2, "./compressions": 3, "./crc32": 4, "./reader/readerFor": 22, "./support": 30, "./utf8": 31, "./utils": 32 }], 35: [function(e, t, r) {
        "use strict";
        function n2(e3, t2, r2) {
          this.name = e3, this.dir = r2.dir, this.date = r2.date, this.comment = r2.comment, this.unixPermissions = r2.unixPermissions, this.dosPermissions = r2.dosPermissions, this._data = t2, this._dataBinary = r2.binary, this.options = { compression: r2.compression, compressionOptions: r2.compressionOptions };
        }
        var s2 = e("./stream/StreamHelper"), i = e("./stream/DataWorker"), a = e("./utf8"), o = e("./compressedObject"), h = e("./stream/GenericWorker");
        n2.prototype = { internalStream: function(e3) {
          var t2 = null, r2 = "string";
          try {
            if (!e3) throw new Error("No output type specified.");
            var n3 = "string" === (r2 = e3.toLowerCase()) || "text" === r2;
            "binarystring" !== r2 && "text" !== r2 || (r2 = "string"), t2 = this._decompressWorker();
            var i2 = !this._dataBinary;
            i2 && !n3 && (t2 = t2.pipe(new a.Utf8EncodeWorker())), !i2 && n3 && (t2 = t2.pipe(new a.Utf8DecodeWorker()));
          } catch (e4) {
            (t2 = new h("error")).error(e4);
          }
          return new s2(t2, r2, "");
        }, async: function(e3, t2) {
          return this.internalStream(e3).accumulate(t2);
        }, nodeStream: function(e3, t2) {
          return this.internalStream(e3 || "nodebuffer").toNodejsStream(t2);
        }, _compressWorker: function(e3, t2) {
          if (this._data instanceof o && this._data.compression.magic === e3.magic) return this._data.getCompressedWorker();
          var r2 = this._decompressWorker();
          return this._dataBinary || (r2 = r2.pipe(new a.Utf8EncodeWorker())), o.createWorkerFrom(r2, e3, t2);
        }, _decompressWorker: function() {
          return this._data instanceof o ? this._data.getContentWorker() : this._data instanceof h ? this._data : new i(this._data);
        } };
        for (var u = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"], l2 = function() {
          throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
        }, f = 0; f < u.length; f++) n2.prototype[u[f]] = l2;
        t.exports = n2;
      }, { "./compressedObject": 2, "./stream/DataWorker": 27, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31 }], 36: [function(e, l2, t) {
        (function(t2) {
          "use strict";
          var r, n2, e3 = t2.MutationObserver || t2.WebKitMutationObserver;
          if (e3) {
            var i = 0, s2 = new e3(u), a = t2.document.createTextNode("");
            s2.observe(a, { characterData: true }), r = function() {
              a.data = i = ++i % 2;
            };
          } else if (t2.setImmediate || void 0 === t2.MessageChannel) r = "document" in t2 && "onreadystatechange" in t2.document.createElement("script") ? function() {
            var e4 = t2.document.createElement("script");
            e4.onreadystatechange = function() {
              u(), e4.onreadystatechange = null, e4.parentNode.removeChild(e4), e4 = null;
            }, t2.document.documentElement.appendChild(e4);
          } : function() {
            setTimeout(u, 0);
          };
          else {
            var o = new t2.MessageChannel();
            o.port1.onmessage = u, r = function() {
              o.port2.postMessage(0);
            };
          }
          var h = [];
          function u() {
            var e4, t3;
            n2 = true;
            for (var r2 = h.length; r2; ) {
              for (t3 = h, h = [], e4 = -1; ++e4 < r2; ) t3[e4]();
              r2 = h.length;
            }
            n2 = false;
          }
          l2.exports = function(e4) {
            1 !== h.push(e4) || n2 || r();
          };
        }).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
      }, {}], 37: [function(e, t, r) {
        "use strict";
        var i = e("immediate");
        function u() {
        }
        var l2 = {}, s2 = ["REJECTED"], a = ["FULFILLED"], n2 = ["PENDING"];
        function o(e3) {
          if ("function" != typeof e3) throw new TypeError("resolver must be a function");
          this.state = n2, this.queue = [], this.outcome = void 0, e3 !== u && d(this, e3);
        }
        function h(e3, t2, r2) {
          this.promise = e3, "function" == typeof t2 && (this.onFulfilled = t2, this.callFulfilled = this.otherCallFulfilled), "function" == typeof r2 && (this.onRejected = r2, this.callRejected = this.otherCallRejected);
        }
        function f(t2, r2, n3) {
          i(function() {
            var e3;
            try {
              e3 = r2(n3);
            } catch (e4) {
              return l2.reject(t2, e4);
            }
            e3 === t2 ? l2.reject(t2, new TypeError("Cannot resolve promise with itself")) : l2.resolve(t2, e3);
          });
        }
        function c(e3) {
          var t2 = e3 && e3.then;
          if (e3 && ("object" == typeof e3 || "function" == typeof e3) && "function" == typeof t2) return function() {
            t2.apply(e3, arguments);
          };
        }
        function d(t2, e3) {
          var r2 = false;
          function n3(e4) {
            r2 || (r2 = true, l2.reject(t2, e4));
          }
          function i2(e4) {
            r2 || (r2 = true, l2.resolve(t2, e4));
          }
          var s3 = p(function() {
            e3(i2, n3);
          });
          "error" === s3.status && n3(s3.value);
        }
        function p(e3, t2) {
          var r2 = {};
          try {
            r2.value = e3(t2), r2.status = "success";
          } catch (e4) {
            r2.status = "error", r2.value = e4;
          }
          return r2;
        }
        (t.exports = o).prototype.finally = function(t2) {
          if ("function" != typeof t2) return this;
          var r2 = this.constructor;
          return this.then(function(e3) {
            return r2.resolve(t2()).then(function() {
              return e3;
            });
          }, function(e3) {
            return r2.resolve(t2()).then(function() {
              throw e3;
            });
          });
        }, o.prototype.catch = function(e3) {
          return this.then(null, e3);
        }, o.prototype.then = function(e3, t2) {
          if ("function" != typeof e3 && this.state === a || "function" != typeof t2 && this.state === s2) return this;
          var r2 = new this.constructor(u);
          this.state !== n2 ? f(r2, this.state === a ? e3 : t2, this.outcome) : this.queue.push(new h(r2, e3, t2));
          return r2;
        }, h.prototype.callFulfilled = function(e3) {
          l2.resolve(this.promise, e3);
        }, h.prototype.otherCallFulfilled = function(e3) {
          f(this.promise, this.onFulfilled, e3);
        }, h.prototype.callRejected = function(e3) {
          l2.reject(this.promise, e3);
        }, h.prototype.otherCallRejected = function(e3) {
          f(this.promise, this.onRejected, e3);
        }, l2.resolve = function(e3, t2) {
          var r2 = p(c, t2);
          if ("error" === r2.status) return l2.reject(e3, r2.value);
          var n3 = r2.value;
          if (n3) d(e3, n3);
          else {
            e3.state = a, e3.outcome = t2;
            for (var i2 = -1, s3 = e3.queue.length; ++i2 < s3; ) e3.queue[i2].callFulfilled(t2);
          }
          return e3;
        }, l2.reject = function(e3, t2) {
          e3.state = s2, e3.outcome = t2;
          for (var r2 = -1, n3 = e3.queue.length; ++r2 < n3; ) e3.queue[r2].callRejected(t2);
          return e3;
        }, o.resolve = function(e3) {
          if (e3 instanceof this) return e3;
          return l2.resolve(new this(u), e3);
        }, o.reject = function(e3) {
          var t2 = new this(u);
          return l2.reject(t2, e3);
        }, o.all = function(e3) {
          var r2 = this;
          if ("[object Array]" !== Object.prototype.toString.call(e3)) return this.reject(new TypeError("must be an array"));
          var n3 = e3.length, i2 = false;
          if (!n3) return this.resolve([]);
          var s3 = new Array(n3), a2 = 0, t2 = -1, o2 = new this(u);
          for (; ++t2 < n3; ) h2(e3[t2], t2);
          return o2;
          function h2(e4, t3) {
            r2.resolve(e4).then(function(e6) {
              s3[t3] = e6, ++a2 !== n3 || i2 || (i2 = true, l2.resolve(o2, s3));
            }, function(e6) {
              i2 || (i2 = true, l2.reject(o2, e6));
            });
          }
        }, o.race = function(e3) {
          var t2 = this;
          if ("[object Array]" !== Object.prototype.toString.call(e3)) return this.reject(new TypeError("must be an array"));
          var r2 = e3.length, n3 = false;
          if (!r2) return this.resolve([]);
          var i2 = -1, s3 = new this(u);
          for (; ++i2 < r2; ) a2 = e3[i2], t2.resolve(a2).then(function(e4) {
            n3 || (n3 = true, l2.resolve(s3, e4));
          }, function(e4) {
            n3 || (n3 = true, l2.reject(s3, e4));
          });
          var a2;
          return s3;
        };
      }, { immediate: 36 }], 38: [function(e, t, r) {
        "use strict";
        var n2 = {};
        (0, e("./lib/utils/common").assign)(n2, e("./lib/deflate"), e("./lib/inflate"), e("./lib/zlib/constants")), t.exports = n2;
      }, { "./lib/deflate": 39, "./lib/inflate": 40, "./lib/utils/common": 41, "./lib/zlib/constants": 44 }], 39: [function(e, t, r) {
        "use strict";
        var a = e("./zlib/deflate"), o = e("./utils/common"), h = e("./utils/strings"), i = e("./zlib/messages"), s2 = e("./zlib/zstream"), u = Object.prototype.toString, l2 = 0, f = -1, c = 0, d = 8;
        function p(e3) {
          if (!(this instanceof p)) return new p(e3);
          this.options = o.assign({ level: f, method: d, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: c, to: "" }, e3 || {});
          var t2 = this.options;
          t2.raw && 0 < t2.windowBits ? t2.windowBits = -t2.windowBits : t2.gzip && 0 < t2.windowBits && t2.windowBits < 16 && (t2.windowBits += 16), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new s2(), this.strm.avail_out = 0;
          var r2 = a.deflateInit2(this.strm, t2.level, t2.method, t2.windowBits, t2.memLevel, t2.strategy);
          if (r2 !== l2) throw new Error(i[r2]);
          if (t2.header && a.deflateSetHeader(this.strm, t2.header), t2.dictionary) {
            var n3;
            if (n3 = "string" == typeof t2.dictionary ? h.string2buf(t2.dictionary) : "[object ArrayBuffer]" === u.call(t2.dictionary) ? new Uint8Array(t2.dictionary) : t2.dictionary, (r2 = a.deflateSetDictionary(this.strm, n3)) !== l2) throw new Error(i[r2]);
            this._dict_set = true;
          }
        }
        function n2(e3, t2) {
          var r2 = new p(t2);
          if (r2.push(e3, true), r2.err) throw r2.msg || i[r2.err];
          return r2.result;
        }
        p.prototype.push = function(e3, t2) {
          var r2, n3, i2 = this.strm, s3 = this.options.chunkSize;
          if (this.ended) return false;
          n3 = t2 === ~~t2 ? t2 : true === t2 ? 4 : 0, "string" == typeof e3 ? i2.input = h.string2buf(e3) : "[object ArrayBuffer]" === u.call(e3) ? i2.input = new Uint8Array(e3) : i2.input = e3, i2.next_in = 0, i2.avail_in = i2.input.length;
          do {
            if (0 === i2.avail_out && (i2.output = new o.Buf8(s3), i2.next_out = 0, i2.avail_out = s3), 1 !== (r2 = a.deflate(i2, n3)) && r2 !== l2) return this.onEnd(r2), !(this.ended = true);
            0 !== i2.avail_out && (0 !== i2.avail_in || 4 !== n3 && 2 !== n3) || ("string" === this.options.to ? this.onData(h.buf2binstring(o.shrinkBuf(i2.output, i2.next_out))) : this.onData(o.shrinkBuf(i2.output, i2.next_out)));
          } while ((0 < i2.avail_in || 0 === i2.avail_out) && 1 !== r2);
          return 4 === n3 ? (r2 = a.deflateEnd(this.strm), this.onEnd(r2), this.ended = true, r2 === l2) : 2 !== n3 || (this.onEnd(l2), !(i2.avail_out = 0));
        }, p.prototype.onData = function(e3) {
          this.chunks.push(e3);
        }, p.prototype.onEnd = function(e3) {
          e3 === l2 && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = o.flattenChunks(this.chunks)), this.chunks = [], this.err = e3, this.msg = this.strm.msg;
        }, r.Deflate = p, r.deflate = n2, r.deflateRaw = function(e3, t2) {
          return (t2 = t2 || {}).raw = true, n2(e3, t2);
        }, r.gzip = function(e3, t2) {
          return (t2 = t2 || {}).gzip = true, n2(e3, t2);
        };
      }, { "./utils/common": 41, "./utils/strings": 42, "./zlib/deflate": 46, "./zlib/messages": 51, "./zlib/zstream": 53 }], 40: [function(e, t, r) {
        "use strict";
        var c = e("./zlib/inflate"), d = e("./utils/common"), p = e("./utils/strings"), m = e("./zlib/constants"), n2 = e("./zlib/messages"), i = e("./zlib/zstream"), s2 = e("./zlib/gzheader"), _ = Object.prototype.toString;
        function a(e3) {
          if (!(this instanceof a)) return new a(e3);
          this.options = d.assign({ chunkSize: 16384, windowBits: 0, to: "" }, e3 || {});
          var t2 = this.options;
          t2.raw && 0 <= t2.windowBits && t2.windowBits < 16 && (t2.windowBits = -t2.windowBits, 0 === t2.windowBits && (t2.windowBits = -15)), !(0 <= t2.windowBits && t2.windowBits < 16) || e3 && e3.windowBits || (t2.windowBits += 32), 15 < t2.windowBits && t2.windowBits < 48 && 0 == (15 & t2.windowBits) && (t2.windowBits |= 15), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new i(), this.strm.avail_out = 0;
          var r2 = c.inflateInit2(this.strm, t2.windowBits);
          if (r2 !== m.Z_OK) throw new Error(n2[r2]);
          this.header = new s2(), c.inflateGetHeader(this.strm, this.header);
        }
        function o(e3, t2) {
          var r2 = new a(t2);
          if (r2.push(e3, true), r2.err) throw r2.msg || n2[r2.err];
          return r2.result;
        }
        a.prototype.push = function(e3, t2) {
          var r2, n3, i2, s3, a2, o2, h = this.strm, u = this.options.chunkSize, l2 = this.options.dictionary, f = false;
          if (this.ended) return false;
          n3 = t2 === ~~t2 ? t2 : true === t2 ? m.Z_FINISH : m.Z_NO_FLUSH, "string" == typeof e3 ? h.input = p.binstring2buf(e3) : "[object ArrayBuffer]" === _.call(e3) ? h.input = new Uint8Array(e3) : h.input = e3, h.next_in = 0, h.avail_in = h.input.length;
          do {
            if (0 === h.avail_out && (h.output = new d.Buf8(u), h.next_out = 0, h.avail_out = u), (r2 = c.inflate(h, m.Z_NO_FLUSH)) === m.Z_NEED_DICT && l2 && (o2 = "string" == typeof l2 ? p.string2buf(l2) : "[object ArrayBuffer]" === _.call(l2) ? new Uint8Array(l2) : l2, r2 = c.inflateSetDictionary(this.strm, o2)), r2 === m.Z_BUF_ERROR && true === f && (r2 = m.Z_OK, f = false), r2 !== m.Z_STREAM_END && r2 !== m.Z_OK) return this.onEnd(r2), !(this.ended = true);
            h.next_out && (0 !== h.avail_out && r2 !== m.Z_STREAM_END && (0 !== h.avail_in || n3 !== m.Z_FINISH && n3 !== m.Z_SYNC_FLUSH) || ("string" === this.options.to ? (i2 = p.utf8border(h.output, h.next_out), s3 = h.next_out - i2, a2 = p.buf2string(h.output, i2), h.next_out = s3, h.avail_out = u - s3, s3 && d.arraySet(h.output, h.output, i2, s3, 0), this.onData(a2)) : this.onData(d.shrinkBuf(h.output, h.next_out)))), 0 === h.avail_in && 0 === h.avail_out && (f = true);
          } while ((0 < h.avail_in || 0 === h.avail_out) && r2 !== m.Z_STREAM_END);
          return r2 === m.Z_STREAM_END && (n3 = m.Z_FINISH), n3 === m.Z_FINISH ? (r2 = c.inflateEnd(this.strm), this.onEnd(r2), this.ended = true, r2 === m.Z_OK) : n3 !== m.Z_SYNC_FLUSH || (this.onEnd(m.Z_OK), !(h.avail_out = 0));
        }, a.prototype.onData = function(e3) {
          this.chunks.push(e3);
        }, a.prototype.onEnd = function(e3) {
          e3 === m.Z_OK && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = d.flattenChunks(this.chunks)), this.chunks = [], this.err = e3, this.msg = this.strm.msg;
        }, r.Inflate = a, r.inflate = o, r.inflateRaw = function(e3, t2) {
          return (t2 = t2 || {}).raw = true, o(e3, t2);
        }, r.ungzip = o;
      }, { "./utils/common": 41, "./utils/strings": 42, "./zlib/constants": 44, "./zlib/gzheader": 47, "./zlib/inflate": 49, "./zlib/messages": 51, "./zlib/zstream": 53 }], 41: [function(e, t, r) {
        "use strict";
        var n2 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Int32Array;
        r.assign = function(e3) {
          for (var t2 = Array.prototype.slice.call(arguments, 1); t2.length; ) {
            var r2 = t2.shift();
            if (r2) {
              if ("object" != typeof r2) throw new TypeError(r2 + "must be non-object");
              for (var n3 in r2) r2.hasOwnProperty(n3) && (e3[n3] = r2[n3]);
            }
          }
          return e3;
        }, r.shrinkBuf = function(e3, t2) {
          return e3.length === t2 ? e3 : e3.subarray ? e3.subarray(0, t2) : (e3.length = t2, e3);
        };
        var i = { arraySet: function(e3, t2, r2, n3, i2) {
          if (t2.subarray && e3.subarray) e3.set(t2.subarray(r2, r2 + n3), i2);
          else for (var s3 = 0; s3 < n3; s3++) e3[i2 + s3] = t2[r2 + s3];
        }, flattenChunks: function(e3) {
          var t2, r2, n3, i2, s3, a;
          for (t2 = n3 = 0, r2 = e3.length; t2 < r2; t2++) n3 += e3[t2].length;
          for (a = new Uint8Array(n3), t2 = i2 = 0, r2 = e3.length; t2 < r2; t2++) s3 = e3[t2], a.set(s3, i2), i2 += s3.length;
          return a;
        } }, s2 = { arraySet: function(e3, t2, r2, n3, i2) {
          for (var s3 = 0; s3 < n3; s3++) e3[i2 + s3] = t2[r2 + s3];
        }, flattenChunks: function(e3) {
          return [].concat.apply([], e3);
        } };
        r.setTyped = function(e3) {
          e3 ? (r.Buf8 = Uint8Array, r.Buf16 = Uint16Array, r.Buf32 = Int32Array, r.assign(r, i)) : (r.Buf8 = Array, r.Buf16 = Array, r.Buf32 = Array, r.assign(r, s2));
        }, r.setTyped(n2);
      }, {}], 42: [function(e, t, r) {
        "use strict";
        var h = e("./common"), i = true, s2 = true;
        try {
          String.fromCharCode.apply(null, [0]);
        } catch (e3) {
          i = false;
        }
        try {
          String.fromCharCode.apply(null, new Uint8Array(1));
        } catch (e3) {
          s2 = false;
        }
        for (var u = new h.Buf8(256), n2 = 0; n2 < 256; n2++) u[n2] = 252 <= n2 ? 6 : 248 <= n2 ? 5 : 240 <= n2 ? 4 : 224 <= n2 ? 3 : 192 <= n2 ? 2 : 1;
        function l2(e3, t2) {
          if (t2 < 65537 && (e3.subarray && s2 || !e3.subarray && i)) return String.fromCharCode.apply(null, h.shrinkBuf(e3, t2));
          for (var r2 = "", n3 = 0; n3 < t2; n3++) r2 += String.fromCharCode(e3[n3]);
          return r2;
        }
        u[254] = u[254] = 1, r.string2buf = function(e3) {
          var t2, r2, n3, i2, s3, a = e3.length, o = 0;
          for (i2 = 0; i2 < a; i2++) 55296 == (64512 & (r2 = e3.charCodeAt(i2))) && i2 + 1 < a && 56320 == (64512 & (n3 = e3.charCodeAt(i2 + 1))) && (r2 = 65536 + (r2 - 55296 << 10) + (n3 - 56320), i2++), o += r2 < 128 ? 1 : r2 < 2048 ? 2 : r2 < 65536 ? 3 : 4;
          for (t2 = new h.Buf8(o), i2 = s3 = 0; s3 < o; i2++) 55296 == (64512 & (r2 = e3.charCodeAt(i2))) && i2 + 1 < a && 56320 == (64512 & (n3 = e3.charCodeAt(i2 + 1))) && (r2 = 65536 + (r2 - 55296 << 10) + (n3 - 56320), i2++), r2 < 128 ? t2[s3++] = r2 : (r2 < 2048 ? t2[s3++] = 192 | r2 >>> 6 : (r2 < 65536 ? t2[s3++] = 224 | r2 >>> 12 : (t2[s3++] = 240 | r2 >>> 18, t2[s3++] = 128 | r2 >>> 12 & 63), t2[s3++] = 128 | r2 >>> 6 & 63), t2[s3++] = 128 | 63 & r2);
          return t2;
        }, r.buf2binstring = function(e3) {
          return l2(e3, e3.length);
        }, r.binstring2buf = function(e3) {
          for (var t2 = new h.Buf8(e3.length), r2 = 0, n3 = t2.length; r2 < n3; r2++) t2[r2] = e3.charCodeAt(r2);
          return t2;
        }, r.buf2string = function(e3, t2) {
          var r2, n3, i2, s3, a = t2 || e3.length, o = new Array(2 * a);
          for (r2 = n3 = 0; r2 < a; ) if ((i2 = e3[r2++]) < 128) o[n3++] = i2;
          else if (4 < (s3 = u[i2])) o[n3++] = 65533, r2 += s3 - 1;
          else {
            for (i2 &= 2 === s3 ? 31 : 3 === s3 ? 15 : 7; 1 < s3 && r2 < a; ) i2 = i2 << 6 | 63 & e3[r2++], s3--;
            1 < s3 ? o[n3++] = 65533 : i2 < 65536 ? o[n3++] = i2 : (i2 -= 65536, o[n3++] = 55296 | i2 >> 10 & 1023, o[n3++] = 56320 | 1023 & i2);
          }
          return l2(o, n3);
        }, r.utf8border = function(e3, t2) {
          var r2;
          for ((t2 = t2 || e3.length) > e3.length && (t2 = e3.length), r2 = t2 - 1; 0 <= r2 && 128 == (192 & e3[r2]); ) r2--;
          return r2 < 0 ? t2 : 0 === r2 ? t2 : r2 + u[e3[r2]] > t2 ? r2 : t2;
        };
      }, { "./common": 41 }], 43: [function(e, t, r) {
        "use strict";
        t.exports = function(e3, t2, r2, n2) {
          for (var i = 65535 & e3 | 0, s2 = e3 >>> 16 & 65535 | 0, a = 0; 0 !== r2; ) {
            for (r2 -= a = 2e3 < r2 ? 2e3 : r2; s2 = s2 + (i = i + t2[n2++] | 0) | 0, --a; ) ;
            i %= 65521, s2 %= 65521;
          }
          return i | s2 << 16 | 0;
        };
      }, {}], 44: [function(e, t, r) {
        "use strict";
        t.exports = { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_BUF_ERROR: -5, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, Z_BINARY: 0, Z_TEXT: 1, Z_UNKNOWN: 2, Z_DEFLATED: 8 };
      }, {}], 45: [function(e, t, r) {
        "use strict";
        var o = (function() {
          for (var e3, t2 = [], r2 = 0; r2 < 256; r2++) {
            e3 = r2;
            for (var n2 = 0; n2 < 8; n2++) e3 = 1 & e3 ? 3988292384 ^ e3 >>> 1 : e3 >>> 1;
            t2[r2] = e3;
          }
          return t2;
        })();
        t.exports = function(e3, t2, r2, n2) {
          var i = o, s2 = n2 + r2;
          e3 ^= -1;
          for (var a = n2; a < s2; a++) e3 = e3 >>> 8 ^ i[255 & (e3 ^ t2[a])];
          return -1 ^ e3;
        };
      }, {}], 46: [function(e, t, r) {
        "use strict";
        var h, c = e("../utils/common"), u = e("./trees"), d = e("./adler32"), p = e("./crc32"), n2 = e("./messages"), l2 = 0, f = 4, m = 0, _ = -2, g = -1, b = 4, i = 2, v = 8, y2 = 9, s2 = 286, a = 30, o = 19, w = 2 * s2 + 1, k = 15, x2 = 3, S = 258, z2 = S + x2 + 1, C = 42, E = 113, A = 1, I = 2, O = 3, B = 4;
        function R(e3, t2) {
          return e3.msg = n2[t2], t2;
        }
        function T(e3) {
          return (e3 << 1) - (4 < e3 ? 9 : 0);
        }
        function D(e3) {
          for (var t2 = e3.length; 0 <= --t2; ) e3[t2] = 0;
        }
        function F(e3) {
          var t2 = e3.state, r2 = t2.pending;
          r2 > e3.avail_out && (r2 = e3.avail_out), 0 !== r2 && (c.arraySet(e3.output, t2.pending_buf, t2.pending_out, r2, e3.next_out), e3.next_out += r2, t2.pending_out += r2, e3.total_out += r2, e3.avail_out -= r2, t2.pending -= r2, 0 === t2.pending && (t2.pending_out = 0));
        }
        function N(e3, t2) {
          u._tr_flush_block(e3, 0 <= e3.block_start ? e3.block_start : -1, e3.strstart - e3.block_start, t2), e3.block_start = e3.strstart, F(e3.strm);
        }
        function U(e3, t2) {
          e3.pending_buf[e3.pending++] = t2;
        }
        function P(e3, t2) {
          e3.pending_buf[e3.pending++] = t2 >>> 8 & 255, e3.pending_buf[e3.pending++] = 255 & t2;
        }
        function L3(e3, t2) {
          var r2, n3, i2 = e3.max_chain_length, s3 = e3.strstart, a2 = e3.prev_length, o2 = e3.nice_match, h2 = e3.strstart > e3.w_size - z2 ? e3.strstart - (e3.w_size - z2) : 0, u2 = e3.window, l3 = e3.w_mask, f2 = e3.prev, c2 = e3.strstart + S, d2 = u2[s3 + a2 - 1], p2 = u2[s3 + a2];
          e3.prev_length >= e3.good_match && (i2 >>= 2), o2 > e3.lookahead && (o2 = e3.lookahead);
          do {
            if (u2[(r2 = t2) + a2] === p2 && u2[r2 + a2 - 1] === d2 && u2[r2] === u2[s3] && u2[++r2] === u2[s3 + 1]) {
              s3 += 2, r2++;
              do {
              } while (u2[++s3] === u2[++r2] && u2[++s3] === u2[++r2] && u2[++s3] === u2[++r2] && u2[++s3] === u2[++r2] && u2[++s3] === u2[++r2] && u2[++s3] === u2[++r2] && u2[++s3] === u2[++r2] && u2[++s3] === u2[++r2] && s3 < c2);
              if (n3 = S - (c2 - s3), s3 = c2 - S, a2 < n3) {
                if (e3.match_start = t2, o2 <= (a2 = n3)) break;
                d2 = u2[s3 + a2 - 1], p2 = u2[s3 + a2];
              }
            }
          } while ((t2 = f2[t2 & l3]) > h2 && 0 != --i2);
          return a2 <= e3.lookahead ? a2 : e3.lookahead;
        }
        function j(e3) {
          var t2, r2, n3, i2, s3, a2, o2, h2, u2, l3, f2 = e3.w_size;
          do {
            if (i2 = e3.window_size - e3.lookahead - e3.strstart, e3.strstart >= f2 + (f2 - z2)) {
              for (c.arraySet(e3.window, e3.window, f2, f2, 0), e3.match_start -= f2, e3.strstart -= f2, e3.block_start -= f2, t2 = r2 = e3.hash_size; n3 = e3.head[--t2], e3.head[t2] = f2 <= n3 ? n3 - f2 : 0, --r2; ) ;
              for (t2 = r2 = f2; n3 = e3.prev[--t2], e3.prev[t2] = f2 <= n3 ? n3 - f2 : 0, --r2; ) ;
              i2 += f2;
            }
            if (0 === e3.strm.avail_in) break;
            if (a2 = e3.strm, o2 = e3.window, h2 = e3.strstart + e3.lookahead, u2 = i2, l3 = void 0, l3 = a2.avail_in, u2 < l3 && (l3 = u2), r2 = 0 === l3 ? 0 : (a2.avail_in -= l3, c.arraySet(o2, a2.input, a2.next_in, l3, h2), 1 === a2.state.wrap ? a2.adler = d(a2.adler, o2, l3, h2) : 2 === a2.state.wrap && (a2.adler = p(a2.adler, o2, l3, h2)), a2.next_in += l3, a2.total_in += l3, l3), e3.lookahead += r2, e3.lookahead + e3.insert >= x2) for (s3 = e3.strstart - e3.insert, e3.ins_h = e3.window[s3], e3.ins_h = (e3.ins_h << e3.hash_shift ^ e3.window[s3 + 1]) & e3.hash_mask; e3.insert && (e3.ins_h = (e3.ins_h << e3.hash_shift ^ e3.window[s3 + x2 - 1]) & e3.hash_mask, e3.prev[s3 & e3.w_mask] = e3.head[e3.ins_h], e3.head[e3.ins_h] = s3, s3++, e3.insert--, !(e3.lookahead + e3.insert < x2)); ) ;
          } while (e3.lookahead < z2 && 0 !== e3.strm.avail_in);
        }
        function Z(e3, t2) {
          for (var r2, n3; ; ) {
            if (e3.lookahead < z2) {
              if (j(e3), e3.lookahead < z2 && t2 === l2) return A;
              if (0 === e3.lookahead) break;
            }
            if (r2 = 0, e3.lookahead >= x2 && (e3.ins_h = (e3.ins_h << e3.hash_shift ^ e3.window[e3.strstart + x2 - 1]) & e3.hash_mask, r2 = e3.prev[e3.strstart & e3.w_mask] = e3.head[e3.ins_h], e3.head[e3.ins_h] = e3.strstart), 0 !== r2 && e3.strstart - r2 <= e3.w_size - z2 && (e3.match_length = L3(e3, r2)), e3.match_length >= x2) if (n3 = u._tr_tally(e3, e3.strstart - e3.match_start, e3.match_length - x2), e3.lookahead -= e3.match_length, e3.match_length <= e3.max_lazy_match && e3.lookahead >= x2) {
              for (e3.match_length--; e3.strstart++, e3.ins_h = (e3.ins_h << e3.hash_shift ^ e3.window[e3.strstart + x2 - 1]) & e3.hash_mask, r2 = e3.prev[e3.strstart & e3.w_mask] = e3.head[e3.ins_h], e3.head[e3.ins_h] = e3.strstart, 0 != --e3.match_length; ) ;
              e3.strstart++;
            } else e3.strstart += e3.match_length, e3.match_length = 0, e3.ins_h = e3.window[e3.strstart], e3.ins_h = (e3.ins_h << e3.hash_shift ^ e3.window[e3.strstart + 1]) & e3.hash_mask;
            else n3 = u._tr_tally(e3, 0, e3.window[e3.strstart]), e3.lookahead--, e3.strstart++;
            if (n3 && (N(e3, false), 0 === e3.strm.avail_out)) return A;
          }
          return e3.insert = e3.strstart < x2 - 1 ? e3.strstart : x2 - 1, t2 === f ? (N(e3, true), 0 === e3.strm.avail_out ? O : B) : e3.last_lit && (N(e3, false), 0 === e3.strm.avail_out) ? A : I;
        }
        function W(e3, t2) {
          for (var r2, n3, i2; ; ) {
            if (e3.lookahead < z2) {
              if (j(e3), e3.lookahead < z2 && t2 === l2) return A;
              if (0 === e3.lookahead) break;
            }
            if (r2 = 0, e3.lookahead >= x2 && (e3.ins_h = (e3.ins_h << e3.hash_shift ^ e3.window[e3.strstart + x2 - 1]) & e3.hash_mask, r2 = e3.prev[e3.strstart & e3.w_mask] = e3.head[e3.ins_h], e3.head[e3.ins_h] = e3.strstart), e3.prev_length = e3.match_length, e3.prev_match = e3.match_start, e3.match_length = x2 - 1, 0 !== r2 && e3.prev_length < e3.max_lazy_match && e3.strstart - r2 <= e3.w_size - z2 && (e3.match_length = L3(e3, r2), e3.match_length <= 5 && (1 === e3.strategy || e3.match_length === x2 && 4096 < e3.strstart - e3.match_start) && (e3.match_length = x2 - 1)), e3.prev_length >= x2 && e3.match_length <= e3.prev_length) {
              for (i2 = e3.strstart + e3.lookahead - x2, n3 = u._tr_tally(e3, e3.strstart - 1 - e3.prev_match, e3.prev_length - x2), e3.lookahead -= e3.prev_length - 1, e3.prev_length -= 2; ++e3.strstart <= i2 && (e3.ins_h = (e3.ins_h << e3.hash_shift ^ e3.window[e3.strstart + x2 - 1]) & e3.hash_mask, r2 = e3.prev[e3.strstart & e3.w_mask] = e3.head[e3.ins_h], e3.head[e3.ins_h] = e3.strstart), 0 != --e3.prev_length; ) ;
              if (e3.match_available = 0, e3.match_length = x2 - 1, e3.strstart++, n3 && (N(e3, false), 0 === e3.strm.avail_out)) return A;
            } else if (e3.match_available) {
              if ((n3 = u._tr_tally(e3, 0, e3.window[e3.strstart - 1])) && N(e3, false), e3.strstart++, e3.lookahead--, 0 === e3.strm.avail_out) return A;
            } else e3.match_available = 1, e3.strstart++, e3.lookahead--;
          }
          return e3.match_available && (n3 = u._tr_tally(e3, 0, e3.window[e3.strstart - 1]), e3.match_available = 0), e3.insert = e3.strstart < x2 - 1 ? e3.strstart : x2 - 1, t2 === f ? (N(e3, true), 0 === e3.strm.avail_out ? O : B) : e3.last_lit && (N(e3, false), 0 === e3.strm.avail_out) ? A : I;
        }
        function M(e3, t2, r2, n3, i2) {
          this.good_length = e3, this.max_lazy = t2, this.nice_length = r2, this.max_chain = n3, this.func = i2;
        }
        function H() {
          this.strm = null, this.status = 0, this.pending_buf = null, this.pending_buf_size = 0, this.pending_out = 0, this.pending = 0, this.wrap = 0, this.gzhead = null, this.gzindex = 0, this.method = v, this.last_flush = -1, this.w_size = 0, this.w_bits = 0, this.w_mask = 0, this.window = null, this.window_size = 0, this.prev = null, this.head = null, this.ins_h = 0, this.hash_size = 0, this.hash_bits = 0, this.hash_mask = 0, this.hash_shift = 0, this.block_start = 0, this.match_length = 0, this.prev_match = 0, this.match_available = 0, this.strstart = 0, this.match_start = 0, this.lookahead = 0, this.prev_length = 0, this.max_chain_length = 0, this.max_lazy_match = 0, this.level = 0, this.strategy = 0, this.good_match = 0, this.nice_match = 0, this.dyn_ltree = new c.Buf16(2 * w), this.dyn_dtree = new c.Buf16(2 * (2 * a + 1)), this.bl_tree = new c.Buf16(2 * (2 * o + 1)), D(this.dyn_ltree), D(this.dyn_dtree), D(this.bl_tree), this.l_desc = null, this.d_desc = null, this.bl_desc = null, this.bl_count = new c.Buf16(k + 1), this.heap = new c.Buf16(2 * s2 + 1), D(this.heap), this.heap_len = 0, this.heap_max = 0, this.depth = new c.Buf16(2 * s2 + 1), D(this.depth), this.l_buf = 0, this.lit_bufsize = 0, this.last_lit = 0, this.d_buf = 0, this.opt_len = 0, this.static_len = 0, this.matches = 0, this.insert = 0, this.bi_buf = 0, this.bi_valid = 0;
        }
        function G(e3) {
          var t2;
          return e3 && e3.state ? (e3.total_in = e3.total_out = 0, e3.data_type = i, (t2 = e3.state).pending = 0, t2.pending_out = 0, t2.wrap < 0 && (t2.wrap = -t2.wrap), t2.status = t2.wrap ? C : E, e3.adler = 2 === t2.wrap ? 0 : 1, t2.last_flush = l2, u._tr_init(t2), m) : R(e3, _);
        }
        function K(e3) {
          var t2 = G(e3);
          return t2 === m && (function(e4) {
            e4.window_size = 2 * e4.w_size, D(e4.head), e4.max_lazy_match = h[e4.level].max_lazy, e4.good_match = h[e4.level].good_length, e4.nice_match = h[e4.level].nice_length, e4.max_chain_length = h[e4.level].max_chain, e4.strstart = 0, e4.block_start = 0, e4.lookahead = 0, e4.insert = 0, e4.match_length = e4.prev_length = x2 - 1, e4.match_available = 0, e4.ins_h = 0;
          })(e3.state), t2;
        }
        function Y(e3, t2, r2, n3, i2, s3) {
          if (!e3) return _;
          var a2 = 1;
          if (t2 === g && (t2 = 6), n3 < 0 ? (a2 = 0, n3 = -n3) : 15 < n3 && (a2 = 2, n3 -= 16), i2 < 1 || y2 < i2 || r2 !== v || n3 < 8 || 15 < n3 || t2 < 0 || 9 < t2 || s3 < 0 || b < s3) return R(e3, _);
          8 === n3 && (n3 = 9);
          var o2 = new H();
          return (e3.state = o2).strm = e3, o2.wrap = a2, o2.gzhead = null, o2.w_bits = n3, o2.w_size = 1 << o2.w_bits, o2.w_mask = o2.w_size - 1, o2.hash_bits = i2 + 7, o2.hash_size = 1 << o2.hash_bits, o2.hash_mask = o2.hash_size - 1, o2.hash_shift = ~~((o2.hash_bits + x2 - 1) / x2), o2.window = new c.Buf8(2 * o2.w_size), o2.head = new c.Buf16(o2.hash_size), o2.prev = new c.Buf16(o2.w_size), o2.lit_bufsize = 1 << i2 + 6, o2.pending_buf_size = 4 * o2.lit_bufsize, o2.pending_buf = new c.Buf8(o2.pending_buf_size), o2.d_buf = 1 * o2.lit_bufsize, o2.l_buf = 3 * o2.lit_bufsize, o2.level = t2, o2.strategy = s3, o2.method = r2, K(e3);
        }
        h = [new M(0, 0, 0, 0, function(e3, t2) {
          var r2 = 65535;
          for (r2 > e3.pending_buf_size - 5 && (r2 = e3.pending_buf_size - 5); ; ) {
            if (e3.lookahead <= 1) {
              if (j(e3), 0 === e3.lookahead && t2 === l2) return A;
              if (0 === e3.lookahead) break;
            }
            e3.strstart += e3.lookahead, e3.lookahead = 0;
            var n3 = e3.block_start + r2;
            if ((0 === e3.strstart || e3.strstart >= n3) && (e3.lookahead = e3.strstart - n3, e3.strstart = n3, N(e3, false), 0 === e3.strm.avail_out)) return A;
            if (e3.strstart - e3.block_start >= e3.w_size - z2 && (N(e3, false), 0 === e3.strm.avail_out)) return A;
          }
          return e3.insert = 0, t2 === f ? (N(e3, true), 0 === e3.strm.avail_out ? O : B) : (e3.strstart > e3.block_start && (N(e3, false), e3.strm.avail_out), A);
        }), new M(4, 4, 8, 4, Z), new M(4, 5, 16, 8, Z), new M(4, 6, 32, 32, Z), new M(4, 4, 16, 16, W), new M(8, 16, 32, 32, W), new M(8, 16, 128, 128, W), new M(8, 32, 128, 256, W), new M(32, 128, 258, 1024, W), new M(32, 258, 258, 4096, W)], r.deflateInit = function(e3, t2) {
          return Y(e3, t2, v, 15, 8, 0);
        }, r.deflateInit2 = Y, r.deflateReset = K, r.deflateResetKeep = G, r.deflateSetHeader = function(e3, t2) {
          return e3 && e3.state ? 2 !== e3.state.wrap ? _ : (e3.state.gzhead = t2, m) : _;
        }, r.deflate = function(e3, t2) {
          var r2, n3, i2, s3;
          if (!e3 || !e3.state || 5 < t2 || t2 < 0) return e3 ? R(e3, _) : _;
          if (n3 = e3.state, !e3.output || !e3.input && 0 !== e3.avail_in || 666 === n3.status && t2 !== f) return R(e3, 0 === e3.avail_out ? -5 : _);
          if (n3.strm = e3, r2 = n3.last_flush, n3.last_flush = t2, n3.status === C) if (2 === n3.wrap) e3.adler = 0, U(n3, 31), U(n3, 139), U(n3, 8), n3.gzhead ? (U(n3, (n3.gzhead.text ? 1 : 0) + (n3.gzhead.hcrc ? 2 : 0) + (n3.gzhead.extra ? 4 : 0) + (n3.gzhead.name ? 8 : 0) + (n3.gzhead.comment ? 16 : 0)), U(n3, 255 & n3.gzhead.time), U(n3, n3.gzhead.time >> 8 & 255), U(n3, n3.gzhead.time >> 16 & 255), U(n3, n3.gzhead.time >> 24 & 255), U(n3, 9 === n3.level ? 2 : 2 <= n3.strategy || n3.level < 2 ? 4 : 0), U(n3, 255 & n3.gzhead.os), n3.gzhead.extra && n3.gzhead.extra.length && (U(n3, 255 & n3.gzhead.extra.length), U(n3, n3.gzhead.extra.length >> 8 & 255)), n3.gzhead.hcrc && (e3.adler = p(e3.adler, n3.pending_buf, n3.pending, 0)), n3.gzindex = 0, n3.status = 69) : (U(n3, 0), U(n3, 0), U(n3, 0), U(n3, 0), U(n3, 0), U(n3, 9 === n3.level ? 2 : 2 <= n3.strategy || n3.level < 2 ? 4 : 0), U(n3, 3), n3.status = E);
          else {
            var a2 = v + (n3.w_bits - 8 << 4) << 8;
            a2 |= (2 <= n3.strategy || n3.level < 2 ? 0 : n3.level < 6 ? 1 : 6 === n3.level ? 2 : 3) << 6, 0 !== n3.strstart && (a2 |= 32), a2 += 31 - a2 % 31, n3.status = E, P(n3, a2), 0 !== n3.strstart && (P(n3, e3.adler >>> 16), P(n3, 65535 & e3.adler)), e3.adler = 1;
          }
          if (69 === n3.status) if (n3.gzhead.extra) {
            for (i2 = n3.pending; n3.gzindex < (65535 & n3.gzhead.extra.length) && (n3.pending !== n3.pending_buf_size || (n3.gzhead.hcrc && n3.pending > i2 && (e3.adler = p(e3.adler, n3.pending_buf, n3.pending - i2, i2)), F(e3), i2 = n3.pending, n3.pending !== n3.pending_buf_size)); ) U(n3, 255 & n3.gzhead.extra[n3.gzindex]), n3.gzindex++;
            n3.gzhead.hcrc && n3.pending > i2 && (e3.adler = p(e3.adler, n3.pending_buf, n3.pending - i2, i2)), n3.gzindex === n3.gzhead.extra.length && (n3.gzindex = 0, n3.status = 73);
          } else n3.status = 73;
          if (73 === n3.status) if (n3.gzhead.name) {
            i2 = n3.pending;
            do {
              if (n3.pending === n3.pending_buf_size && (n3.gzhead.hcrc && n3.pending > i2 && (e3.adler = p(e3.adler, n3.pending_buf, n3.pending - i2, i2)), F(e3), i2 = n3.pending, n3.pending === n3.pending_buf_size)) {
                s3 = 1;
                break;
              }
              s3 = n3.gzindex < n3.gzhead.name.length ? 255 & n3.gzhead.name.charCodeAt(n3.gzindex++) : 0, U(n3, s3);
            } while (0 !== s3);
            n3.gzhead.hcrc && n3.pending > i2 && (e3.adler = p(e3.adler, n3.pending_buf, n3.pending - i2, i2)), 0 === s3 && (n3.gzindex = 0, n3.status = 91);
          } else n3.status = 91;
          if (91 === n3.status) if (n3.gzhead.comment) {
            i2 = n3.pending;
            do {
              if (n3.pending === n3.pending_buf_size && (n3.gzhead.hcrc && n3.pending > i2 && (e3.adler = p(e3.adler, n3.pending_buf, n3.pending - i2, i2)), F(e3), i2 = n3.pending, n3.pending === n3.pending_buf_size)) {
                s3 = 1;
                break;
              }
              s3 = n3.gzindex < n3.gzhead.comment.length ? 255 & n3.gzhead.comment.charCodeAt(n3.gzindex++) : 0, U(n3, s3);
            } while (0 !== s3);
            n3.gzhead.hcrc && n3.pending > i2 && (e3.adler = p(e3.adler, n3.pending_buf, n3.pending - i2, i2)), 0 === s3 && (n3.status = 103);
          } else n3.status = 103;
          if (103 === n3.status && (n3.gzhead.hcrc ? (n3.pending + 2 > n3.pending_buf_size && F(e3), n3.pending + 2 <= n3.pending_buf_size && (U(n3, 255 & e3.adler), U(n3, e3.adler >> 8 & 255), e3.adler = 0, n3.status = E)) : n3.status = E), 0 !== n3.pending) {
            if (F(e3), 0 === e3.avail_out) return n3.last_flush = -1, m;
          } else if (0 === e3.avail_in && T(t2) <= T(r2) && t2 !== f) return R(e3, -5);
          if (666 === n3.status && 0 !== e3.avail_in) return R(e3, -5);
          if (0 !== e3.avail_in || 0 !== n3.lookahead || t2 !== l2 && 666 !== n3.status) {
            var o2 = 2 === n3.strategy ? (function(e4, t3) {
              for (var r3; ; ) {
                if (0 === e4.lookahead && (j(e4), 0 === e4.lookahead)) {
                  if (t3 === l2) return A;
                  break;
                }
                if (e4.match_length = 0, r3 = u._tr_tally(e4, 0, e4.window[e4.strstart]), e4.lookahead--, e4.strstart++, r3 && (N(e4, false), 0 === e4.strm.avail_out)) return A;
              }
              return e4.insert = 0, t3 === f ? (N(e4, true), 0 === e4.strm.avail_out ? O : B) : e4.last_lit && (N(e4, false), 0 === e4.strm.avail_out) ? A : I;
            })(n3, t2) : 3 === n3.strategy ? (function(e4, t3) {
              for (var r3, n4, i3, s4, a3 = e4.window; ; ) {
                if (e4.lookahead <= S) {
                  if (j(e4), e4.lookahead <= S && t3 === l2) return A;
                  if (0 === e4.lookahead) break;
                }
                if (e4.match_length = 0, e4.lookahead >= x2 && 0 < e4.strstart && (n4 = a3[i3 = e4.strstart - 1]) === a3[++i3] && n4 === a3[++i3] && n4 === a3[++i3]) {
                  s4 = e4.strstart + S;
                  do {
                  } while (n4 === a3[++i3] && n4 === a3[++i3] && n4 === a3[++i3] && n4 === a3[++i3] && n4 === a3[++i3] && n4 === a3[++i3] && n4 === a3[++i3] && n4 === a3[++i3] && i3 < s4);
                  e4.match_length = S - (s4 - i3), e4.match_length > e4.lookahead && (e4.match_length = e4.lookahead);
                }
                if (e4.match_length >= x2 ? (r3 = u._tr_tally(e4, 1, e4.match_length - x2), e4.lookahead -= e4.match_length, e4.strstart += e4.match_length, e4.match_length = 0) : (r3 = u._tr_tally(e4, 0, e4.window[e4.strstart]), e4.lookahead--, e4.strstart++), r3 && (N(e4, false), 0 === e4.strm.avail_out)) return A;
              }
              return e4.insert = 0, t3 === f ? (N(e4, true), 0 === e4.strm.avail_out ? O : B) : e4.last_lit && (N(e4, false), 0 === e4.strm.avail_out) ? A : I;
            })(n3, t2) : h[n3.level].func(n3, t2);
            if (o2 !== O && o2 !== B || (n3.status = 666), o2 === A || o2 === O) return 0 === e3.avail_out && (n3.last_flush = -1), m;
            if (o2 === I && (1 === t2 ? u._tr_align(n3) : 5 !== t2 && (u._tr_stored_block(n3, 0, 0, false), 3 === t2 && (D(n3.head), 0 === n3.lookahead && (n3.strstart = 0, n3.block_start = 0, n3.insert = 0))), F(e3), 0 === e3.avail_out)) return n3.last_flush = -1, m;
          }
          return t2 !== f ? m : n3.wrap <= 0 ? 1 : (2 === n3.wrap ? (U(n3, 255 & e3.adler), U(n3, e3.adler >> 8 & 255), U(n3, e3.adler >> 16 & 255), U(n3, e3.adler >> 24 & 255), U(n3, 255 & e3.total_in), U(n3, e3.total_in >> 8 & 255), U(n3, e3.total_in >> 16 & 255), U(n3, e3.total_in >> 24 & 255)) : (P(n3, e3.adler >>> 16), P(n3, 65535 & e3.adler)), F(e3), 0 < n3.wrap && (n3.wrap = -n3.wrap), 0 !== n3.pending ? m : 1);
        }, r.deflateEnd = function(e3) {
          var t2;
          return e3 && e3.state ? (t2 = e3.state.status) !== C && 69 !== t2 && 73 !== t2 && 91 !== t2 && 103 !== t2 && t2 !== E && 666 !== t2 ? R(e3, _) : (e3.state = null, t2 === E ? R(e3, -3) : m) : _;
        }, r.deflateSetDictionary = function(e3, t2) {
          var r2, n3, i2, s3, a2, o2, h2, u2, l3 = t2.length;
          if (!e3 || !e3.state) return _;
          if (2 === (s3 = (r2 = e3.state).wrap) || 1 === s3 && r2.status !== C || r2.lookahead) return _;
          for (1 === s3 && (e3.adler = d(e3.adler, t2, l3, 0)), r2.wrap = 0, l3 >= r2.w_size && (0 === s3 && (D(r2.head), r2.strstart = 0, r2.block_start = 0, r2.insert = 0), u2 = new c.Buf8(r2.w_size), c.arraySet(u2, t2, l3 - r2.w_size, r2.w_size, 0), t2 = u2, l3 = r2.w_size), a2 = e3.avail_in, o2 = e3.next_in, h2 = e3.input, e3.avail_in = l3, e3.next_in = 0, e3.input = t2, j(r2); r2.lookahead >= x2; ) {
            for (n3 = r2.strstart, i2 = r2.lookahead - (x2 - 1); r2.ins_h = (r2.ins_h << r2.hash_shift ^ r2.window[n3 + x2 - 1]) & r2.hash_mask, r2.prev[n3 & r2.w_mask] = r2.head[r2.ins_h], r2.head[r2.ins_h] = n3, n3++, --i2; ) ;
            r2.strstart = n3, r2.lookahead = x2 - 1, j(r2);
          }
          return r2.strstart += r2.lookahead, r2.block_start = r2.strstart, r2.insert = r2.lookahead, r2.lookahead = 0, r2.match_length = r2.prev_length = x2 - 1, r2.match_available = 0, e3.next_in = o2, e3.input = h2, e3.avail_in = a2, r2.wrap = s3, m;
        }, r.deflateInfo = "pako deflate (from Nodeca project)";
      }, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./messages": 51, "./trees": 52 }], 47: [function(e, t, r) {
        "use strict";
        t.exports = function() {
          this.text = 0, this.time = 0, this.xflags = 0, this.os = 0, this.extra = null, this.extra_len = 0, this.name = "", this.comment = "", this.hcrc = 0, this.done = false;
        };
      }, {}], 48: [function(e, t, r) {
        "use strict";
        t.exports = function(e3, t2) {
          var r2, n2, i, s2, a, o, h, u, l2, f, c, d, p, m, _, g, b, v, y2, w, k, x2, S, z2, C;
          r2 = e3.state, n2 = e3.next_in, z2 = e3.input, i = n2 + (e3.avail_in - 5), s2 = e3.next_out, C = e3.output, a = s2 - (t2 - e3.avail_out), o = s2 + (e3.avail_out - 257), h = r2.dmax, u = r2.wsize, l2 = r2.whave, f = r2.wnext, c = r2.window, d = r2.hold, p = r2.bits, m = r2.lencode, _ = r2.distcode, g = (1 << r2.lenbits) - 1, b = (1 << r2.distbits) - 1;
          e: do {
            p < 15 && (d += z2[n2++] << p, p += 8, d += z2[n2++] << p, p += 8), v = m[d & g];
            t: for (; ; ) {
              if (d >>>= y2 = v >>> 24, p -= y2, 0 === (y2 = v >>> 16 & 255)) C[s2++] = 65535 & v;
              else {
                if (!(16 & y2)) {
                  if (0 == (64 & y2)) {
                    v = m[(65535 & v) + (d & (1 << y2) - 1)];
                    continue t;
                  }
                  if (32 & y2) {
                    r2.mode = 12;
                    break e;
                  }
                  e3.msg = "invalid literal/length code", r2.mode = 30;
                  break e;
                }
                w = 65535 & v, (y2 &= 15) && (p < y2 && (d += z2[n2++] << p, p += 8), w += d & (1 << y2) - 1, d >>>= y2, p -= y2), p < 15 && (d += z2[n2++] << p, p += 8, d += z2[n2++] << p, p += 8), v = _[d & b];
                r: for (; ; ) {
                  if (d >>>= y2 = v >>> 24, p -= y2, !(16 & (y2 = v >>> 16 & 255))) {
                    if (0 == (64 & y2)) {
                      v = _[(65535 & v) + (d & (1 << y2) - 1)];
                      continue r;
                    }
                    e3.msg = "invalid distance code", r2.mode = 30;
                    break e;
                  }
                  if (k = 65535 & v, p < (y2 &= 15) && (d += z2[n2++] << p, (p += 8) < y2 && (d += z2[n2++] << p, p += 8)), h < (k += d & (1 << y2) - 1)) {
                    e3.msg = "invalid distance too far back", r2.mode = 30;
                    break e;
                  }
                  if (d >>>= y2, p -= y2, (y2 = s2 - a) < k) {
                    if (l2 < (y2 = k - y2) && r2.sane) {
                      e3.msg = "invalid distance too far back", r2.mode = 30;
                      break e;
                    }
                    if (S = c, (x2 = 0) === f) {
                      if (x2 += u - y2, y2 < w) {
                        for (w -= y2; C[s2++] = c[x2++], --y2; ) ;
                        x2 = s2 - k, S = C;
                      }
                    } else if (f < y2) {
                      if (x2 += u + f - y2, (y2 -= f) < w) {
                        for (w -= y2; C[s2++] = c[x2++], --y2; ) ;
                        if (x2 = 0, f < w) {
                          for (w -= y2 = f; C[s2++] = c[x2++], --y2; ) ;
                          x2 = s2 - k, S = C;
                        }
                      }
                    } else if (x2 += f - y2, y2 < w) {
                      for (w -= y2; C[s2++] = c[x2++], --y2; ) ;
                      x2 = s2 - k, S = C;
                    }
                    for (; 2 < w; ) C[s2++] = S[x2++], C[s2++] = S[x2++], C[s2++] = S[x2++], w -= 3;
                    w && (C[s2++] = S[x2++], 1 < w && (C[s2++] = S[x2++]));
                  } else {
                    for (x2 = s2 - k; C[s2++] = C[x2++], C[s2++] = C[x2++], C[s2++] = C[x2++], 2 < (w -= 3); ) ;
                    w && (C[s2++] = C[x2++], 1 < w && (C[s2++] = C[x2++]));
                  }
                  break;
                }
              }
              break;
            }
          } while (n2 < i && s2 < o);
          n2 -= w = p >> 3, d &= (1 << (p -= w << 3)) - 1, e3.next_in = n2, e3.next_out = s2, e3.avail_in = n2 < i ? i - n2 + 5 : 5 - (n2 - i), e3.avail_out = s2 < o ? o - s2 + 257 : 257 - (s2 - o), r2.hold = d, r2.bits = p;
        };
      }, {}], 49: [function(e, t, r) {
        "use strict";
        var I = e("../utils/common"), O = e("./adler32"), B = e("./crc32"), R = e("./inffast"), T = e("./inftrees"), D = 1, F = 2, N = 0, U = -2, P = 1, n2 = 852, i = 592;
        function L3(e3) {
          return (e3 >>> 24 & 255) + (e3 >>> 8 & 65280) + ((65280 & e3) << 8) + ((255 & e3) << 24);
        }
        function s2() {
          this.mode = 0, this.last = false, this.wrap = 0, this.havedict = false, this.flags = 0, this.dmax = 0, this.check = 0, this.total = 0, this.head = null, this.wbits = 0, this.wsize = 0, this.whave = 0, this.wnext = 0, this.window = null, this.hold = 0, this.bits = 0, this.length = 0, this.offset = 0, this.extra = 0, this.lencode = null, this.distcode = null, this.lenbits = 0, this.distbits = 0, this.ncode = 0, this.nlen = 0, this.ndist = 0, this.have = 0, this.next = null, this.lens = new I.Buf16(320), this.work = new I.Buf16(288), this.lendyn = null, this.distdyn = null, this.sane = 0, this.back = 0, this.was = 0;
        }
        function a(e3) {
          var t2;
          return e3 && e3.state ? (t2 = e3.state, e3.total_in = e3.total_out = t2.total = 0, e3.msg = "", t2.wrap && (e3.adler = 1 & t2.wrap), t2.mode = P, t2.last = 0, t2.havedict = 0, t2.dmax = 32768, t2.head = null, t2.hold = 0, t2.bits = 0, t2.lencode = t2.lendyn = new I.Buf32(n2), t2.distcode = t2.distdyn = new I.Buf32(i), t2.sane = 1, t2.back = -1, N) : U;
        }
        function o(e3) {
          var t2;
          return e3 && e3.state ? ((t2 = e3.state).wsize = 0, t2.whave = 0, t2.wnext = 0, a(e3)) : U;
        }
        function h(e3, t2) {
          var r2, n3;
          return e3 && e3.state ? (n3 = e3.state, t2 < 0 ? (r2 = 0, t2 = -t2) : (r2 = 1 + (t2 >> 4), t2 < 48 && (t2 &= 15)), t2 && (t2 < 8 || 15 < t2) ? U : (null !== n3.window && n3.wbits !== t2 && (n3.window = null), n3.wrap = r2, n3.wbits = t2, o(e3))) : U;
        }
        function u(e3, t2) {
          var r2, n3;
          return e3 ? (n3 = new s2(), (e3.state = n3).window = null, (r2 = h(e3, t2)) !== N && (e3.state = null), r2) : U;
        }
        var l2, f, c = true;
        function j(e3) {
          if (c) {
            var t2;
            for (l2 = new I.Buf32(512), f = new I.Buf32(32), t2 = 0; t2 < 144; ) e3.lens[t2++] = 8;
            for (; t2 < 256; ) e3.lens[t2++] = 9;
            for (; t2 < 280; ) e3.lens[t2++] = 7;
            for (; t2 < 288; ) e3.lens[t2++] = 8;
            for (T(D, e3.lens, 0, 288, l2, 0, e3.work, { bits: 9 }), t2 = 0; t2 < 32; ) e3.lens[t2++] = 5;
            T(F, e3.lens, 0, 32, f, 0, e3.work, { bits: 5 }), c = false;
          }
          e3.lencode = l2, e3.lenbits = 9, e3.distcode = f, e3.distbits = 5;
        }
        function Z(e3, t2, r2, n3) {
          var i2, s3 = e3.state;
          return null === s3.window && (s3.wsize = 1 << s3.wbits, s3.wnext = 0, s3.whave = 0, s3.window = new I.Buf8(s3.wsize)), n3 >= s3.wsize ? (I.arraySet(s3.window, t2, r2 - s3.wsize, s3.wsize, 0), s3.wnext = 0, s3.whave = s3.wsize) : (n3 < (i2 = s3.wsize - s3.wnext) && (i2 = n3), I.arraySet(s3.window, t2, r2 - n3, i2, s3.wnext), (n3 -= i2) ? (I.arraySet(s3.window, t2, r2 - n3, n3, 0), s3.wnext = n3, s3.whave = s3.wsize) : (s3.wnext += i2, s3.wnext === s3.wsize && (s3.wnext = 0), s3.whave < s3.wsize && (s3.whave += i2))), 0;
        }
        r.inflateReset = o, r.inflateReset2 = h, r.inflateResetKeep = a, r.inflateInit = function(e3) {
          return u(e3, 15);
        }, r.inflateInit2 = u, r.inflate = function(e3, t2) {
          var r2, n3, i2, s3, a2, o2, h2, u2, l3, f2, c2, d, p, m, _, g, b, v, y2, w, k, x2, S, z2, C = 0, E = new I.Buf8(4), A = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
          if (!e3 || !e3.state || !e3.output || !e3.input && 0 !== e3.avail_in) return U;
          12 === (r2 = e3.state).mode && (r2.mode = 13), a2 = e3.next_out, i2 = e3.output, h2 = e3.avail_out, s3 = e3.next_in, n3 = e3.input, o2 = e3.avail_in, u2 = r2.hold, l3 = r2.bits, f2 = o2, c2 = h2, x2 = N;
          e: for (; ; ) switch (r2.mode) {
            case P:
              if (0 === r2.wrap) {
                r2.mode = 13;
                break;
              }
              for (; l3 < 16; ) {
                if (0 === o2) break e;
                o2--, u2 += n3[s3++] << l3, l3 += 8;
              }
              if (2 & r2.wrap && 35615 === u2) {
                E[r2.check = 0] = 255 & u2, E[1] = u2 >>> 8 & 255, r2.check = B(r2.check, E, 2, 0), l3 = u2 = 0, r2.mode = 2;
                break;
              }
              if (r2.flags = 0, r2.head && (r2.head.done = false), !(1 & r2.wrap) || (((255 & u2) << 8) + (u2 >> 8)) % 31) {
                e3.msg = "incorrect header check", r2.mode = 30;
                break;
              }
              if (8 != (15 & u2)) {
                e3.msg = "unknown compression method", r2.mode = 30;
                break;
              }
              if (l3 -= 4, k = 8 + (15 & (u2 >>>= 4)), 0 === r2.wbits) r2.wbits = k;
              else if (k > r2.wbits) {
                e3.msg = "invalid window size", r2.mode = 30;
                break;
              }
              r2.dmax = 1 << k, e3.adler = r2.check = 1, r2.mode = 512 & u2 ? 10 : 12, l3 = u2 = 0;
              break;
            case 2:
              for (; l3 < 16; ) {
                if (0 === o2) break e;
                o2--, u2 += n3[s3++] << l3, l3 += 8;
              }
              if (r2.flags = u2, 8 != (255 & r2.flags)) {
                e3.msg = "unknown compression method", r2.mode = 30;
                break;
              }
              if (57344 & r2.flags) {
                e3.msg = "unknown header flags set", r2.mode = 30;
                break;
              }
              r2.head && (r2.head.text = u2 >> 8 & 1), 512 & r2.flags && (E[0] = 255 & u2, E[1] = u2 >>> 8 & 255, r2.check = B(r2.check, E, 2, 0)), l3 = u2 = 0, r2.mode = 3;
            case 3:
              for (; l3 < 32; ) {
                if (0 === o2) break e;
                o2--, u2 += n3[s3++] << l3, l3 += 8;
              }
              r2.head && (r2.head.time = u2), 512 & r2.flags && (E[0] = 255 & u2, E[1] = u2 >>> 8 & 255, E[2] = u2 >>> 16 & 255, E[3] = u2 >>> 24 & 255, r2.check = B(r2.check, E, 4, 0)), l3 = u2 = 0, r2.mode = 4;
            case 4:
              for (; l3 < 16; ) {
                if (0 === o2) break e;
                o2--, u2 += n3[s3++] << l3, l3 += 8;
              }
              r2.head && (r2.head.xflags = 255 & u2, r2.head.os = u2 >> 8), 512 & r2.flags && (E[0] = 255 & u2, E[1] = u2 >>> 8 & 255, r2.check = B(r2.check, E, 2, 0)), l3 = u2 = 0, r2.mode = 5;
            case 5:
              if (1024 & r2.flags) {
                for (; l3 < 16; ) {
                  if (0 === o2) break e;
                  o2--, u2 += n3[s3++] << l3, l3 += 8;
                }
                r2.length = u2, r2.head && (r2.head.extra_len = u2), 512 & r2.flags && (E[0] = 255 & u2, E[1] = u2 >>> 8 & 255, r2.check = B(r2.check, E, 2, 0)), l3 = u2 = 0;
              } else r2.head && (r2.head.extra = null);
              r2.mode = 6;
            case 6:
              if (1024 & r2.flags && (o2 < (d = r2.length) && (d = o2), d && (r2.head && (k = r2.head.extra_len - r2.length, r2.head.extra || (r2.head.extra = new Array(r2.head.extra_len)), I.arraySet(r2.head.extra, n3, s3, d, k)), 512 & r2.flags && (r2.check = B(r2.check, n3, d, s3)), o2 -= d, s3 += d, r2.length -= d), r2.length)) break e;
              r2.length = 0, r2.mode = 7;
            case 7:
              if (2048 & r2.flags) {
                if (0 === o2) break e;
                for (d = 0; k = n3[s3 + d++], r2.head && k && r2.length < 65536 && (r2.head.name += String.fromCharCode(k)), k && d < o2; ) ;
                if (512 & r2.flags && (r2.check = B(r2.check, n3, d, s3)), o2 -= d, s3 += d, k) break e;
              } else r2.head && (r2.head.name = null);
              r2.length = 0, r2.mode = 8;
            case 8:
              if (4096 & r2.flags) {
                if (0 === o2) break e;
                for (d = 0; k = n3[s3 + d++], r2.head && k && r2.length < 65536 && (r2.head.comment += String.fromCharCode(k)), k && d < o2; ) ;
                if (512 & r2.flags && (r2.check = B(r2.check, n3, d, s3)), o2 -= d, s3 += d, k) break e;
              } else r2.head && (r2.head.comment = null);
              r2.mode = 9;
            case 9:
              if (512 & r2.flags) {
                for (; l3 < 16; ) {
                  if (0 === o2) break e;
                  o2--, u2 += n3[s3++] << l3, l3 += 8;
                }
                if (u2 !== (65535 & r2.check)) {
                  e3.msg = "header crc mismatch", r2.mode = 30;
                  break;
                }
                l3 = u2 = 0;
              }
              r2.head && (r2.head.hcrc = r2.flags >> 9 & 1, r2.head.done = true), e3.adler = r2.check = 0, r2.mode = 12;
              break;
            case 10:
              for (; l3 < 32; ) {
                if (0 === o2) break e;
                o2--, u2 += n3[s3++] << l3, l3 += 8;
              }
              e3.adler = r2.check = L3(u2), l3 = u2 = 0, r2.mode = 11;
            case 11:
              if (0 === r2.havedict) return e3.next_out = a2, e3.avail_out = h2, e3.next_in = s3, e3.avail_in = o2, r2.hold = u2, r2.bits = l3, 2;
              e3.adler = r2.check = 1, r2.mode = 12;
            case 12:
              if (5 === t2 || 6 === t2) break e;
            case 13:
              if (r2.last) {
                u2 >>>= 7 & l3, l3 -= 7 & l3, r2.mode = 27;
                break;
              }
              for (; l3 < 3; ) {
                if (0 === o2) break e;
                o2--, u2 += n3[s3++] << l3, l3 += 8;
              }
              switch (r2.last = 1 & u2, l3 -= 1, 3 & (u2 >>>= 1)) {
                case 0:
                  r2.mode = 14;
                  break;
                case 1:
                  if (j(r2), r2.mode = 20, 6 !== t2) break;
                  u2 >>>= 2, l3 -= 2;
                  break e;
                case 2:
                  r2.mode = 17;
                  break;
                case 3:
                  e3.msg = "invalid block type", r2.mode = 30;
              }
              u2 >>>= 2, l3 -= 2;
              break;
            case 14:
              for (u2 >>>= 7 & l3, l3 -= 7 & l3; l3 < 32; ) {
                if (0 === o2) break e;
                o2--, u2 += n3[s3++] << l3, l3 += 8;
              }
              if ((65535 & u2) != (u2 >>> 16 ^ 65535)) {
                e3.msg = "invalid stored block lengths", r2.mode = 30;
                break;
              }
              if (r2.length = 65535 & u2, l3 = u2 = 0, r2.mode = 15, 6 === t2) break e;
            case 15:
              r2.mode = 16;
            case 16:
              if (d = r2.length) {
                if (o2 < d && (d = o2), h2 < d && (d = h2), 0 === d) break e;
                I.arraySet(i2, n3, s3, d, a2), o2 -= d, s3 += d, h2 -= d, a2 += d, r2.length -= d;
                break;
              }
              r2.mode = 12;
              break;
            case 17:
              for (; l3 < 14; ) {
                if (0 === o2) break e;
                o2--, u2 += n3[s3++] << l3, l3 += 8;
              }
              if (r2.nlen = 257 + (31 & u2), u2 >>>= 5, l3 -= 5, r2.ndist = 1 + (31 & u2), u2 >>>= 5, l3 -= 5, r2.ncode = 4 + (15 & u2), u2 >>>= 4, l3 -= 4, 286 < r2.nlen || 30 < r2.ndist) {
                e3.msg = "too many length or distance symbols", r2.mode = 30;
                break;
              }
              r2.have = 0, r2.mode = 18;
            case 18:
              for (; r2.have < r2.ncode; ) {
                for (; l3 < 3; ) {
                  if (0 === o2) break e;
                  o2--, u2 += n3[s3++] << l3, l3 += 8;
                }
                r2.lens[A[r2.have++]] = 7 & u2, u2 >>>= 3, l3 -= 3;
              }
              for (; r2.have < 19; ) r2.lens[A[r2.have++]] = 0;
              if (r2.lencode = r2.lendyn, r2.lenbits = 7, S = { bits: r2.lenbits }, x2 = T(0, r2.lens, 0, 19, r2.lencode, 0, r2.work, S), r2.lenbits = S.bits, x2) {
                e3.msg = "invalid code lengths set", r2.mode = 30;
                break;
              }
              r2.have = 0, r2.mode = 19;
            case 19:
              for (; r2.have < r2.nlen + r2.ndist; ) {
                for (; g = (C = r2.lencode[u2 & (1 << r2.lenbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l3); ) {
                  if (0 === o2) break e;
                  o2--, u2 += n3[s3++] << l3, l3 += 8;
                }
                if (b < 16) u2 >>>= _, l3 -= _, r2.lens[r2.have++] = b;
                else {
                  if (16 === b) {
                    for (z2 = _ + 2; l3 < z2; ) {
                      if (0 === o2) break e;
                      o2--, u2 += n3[s3++] << l3, l3 += 8;
                    }
                    if (u2 >>>= _, l3 -= _, 0 === r2.have) {
                      e3.msg = "invalid bit length repeat", r2.mode = 30;
                      break;
                    }
                    k = r2.lens[r2.have - 1], d = 3 + (3 & u2), u2 >>>= 2, l3 -= 2;
                  } else if (17 === b) {
                    for (z2 = _ + 3; l3 < z2; ) {
                      if (0 === o2) break e;
                      o2--, u2 += n3[s3++] << l3, l3 += 8;
                    }
                    l3 -= _, k = 0, d = 3 + (7 & (u2 >>>= _)), u2 >>>= 3, l3 -= 3;
                  } else {
                    for (z2 = _ + 7; l3 < z2; ) {
                      if (0 === o2) break e;
                      o2--, u2 += n3[s3++] << l3, l3 += 8;
                    }
                    l3 -= _, k = 0, d = 11 + (127 & (u2 >>>= _)), u2 >>>= 7, l3 -= 7;
                  }
                  if (r2.have + d > r2.nlen + r2.ndist) {
                    e3.msg = "invalid bit length repeat", r2.mode = 30;
                    break;
                  }
                  for (; d--; ) r2.lens[r2.have++] = k;
                }
              }
              if (30 === r2.mode) break;
              if (0 === r2.lens[256]) {
                e3.msg = "invalid code -- missing end-of-block", r2.mode = 30;
                break;
              }
              if (r2.lenbits = 9, S = { bits: r2.lenbits }, x2 = T(D, r2.lens, 0, r2.nlen, r2.lencode, 0, r2.work, S), r2.lenbits = S.bits, x2) {
                e3.msg = "invalid literal/lengths set", r2.mode = 30;
                break;
              }
              if (r2.distbits = 6, r2.distcode = r2.distdyn, S = { bits: r2.distbits }, x2 = T(F, r2.lens, r2.nlen, r2.ndist, r2.distcode, 0, r2.work, S), r2.distbits = S.bits, x2) {
                e3.msg = "invalid distances set", r2.mode = 30;
                break;
              }
              if (r2.mode = 20, 6 === t2) break e;
            case 20:
              r2.mode = 21;
            case 21:
              if (6 <= o2 && 258 <= h2) {
                e3.next_out = a2, e3.avail_out = h2, e3.next_in = s3, e3.avail_in = o2, r2.hold = u2, r2.bits = l3, R(e3, c2), a2 = e3.next_out, i2 = e3.output, h2 = e3.avail_out, s3 = e3.next_in, n3 = e3.input, o2 = e3.avail_in, u2 = r2.hold, l3 = r2.bits, 12 === r2.mode && (r2.back = -1);
                break;
              }
              for (r2.back = 0; g = (C = r2.lencode[u2 & (1 << r2.lenbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l3); ) {
                if (0 === o2) break e;
                o2--, u2 += n3[s3++] << l3, l3 += 8;
              }
              if (g && 0 == (240 & g)) {
                for (v = _, y2 = g, w = b; g = (C = r2.lencode[w + ((u2 & (1 << v + y2) - 1) >> v)]) >>> 16 & 255, b = 65535 & C, !(v + (_ = C >>> 24) <= l3); ) {
                  if (0 === o2) break e;
                  o2--, u2 += n3[s3++] << l3, l3 += 8;
                }
                u2 >>>= v, l3 -= v, r2.back += v;
              }
              if (u2 >>>= _, l3 -= _, r2.back += _, r2.length = b, 0 === g) {
                r2.mode = 26;
                break;
              }
              if (32 & g) {
                r2.back = -1, r2.mode = 12;
                break;
              }
              if (64 & g) {
                e3.msg = "invalid literal/length code", r2.mode = 30;
                break;
              }
              r2.extra = 15 & g, r2.mode = 22;
            case 22:
              if (r2.extra) {
                for (z2 = r2.extra; l3 < z2; ) {
                  if (0 === o2) break e;
                  o2--, u2 += n3[s3++] << l3, l3 += 8;
                }
                r2.length += u2 & (1 << r2.extra) - 1, u2 >>>= r2.extra, l3 -= r2.extra, r2.back += r2.extra;
              }
              r2.was = r2.length, r2.mode = 23;
            case 23:
              for (; g = (C = r2.distcode[u2 & (1 << r2.distbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l3); ) {
                if (0 === o2) break e;
                o2--, u2 += n3[s3++] << l3, l3 += 8;
              }
              if (0 == (240 & g)) {
                for (v = _, y2 = g, w = b; g = (C = r2.distcode[w + ((u2 & (1 << v + y2) - 1) >> v)]) >>> 16 & 255, b = 65535 & C, !(v + (_ = C >>> 24) <= l3); ) {
                  if (0 === o2) break e;
                  o2--, u2 += n3[s3++] << l3, l3 += 8;
                }
                u2 >>>= v, l3 -= v, r2.back += v;
              }
              if (u2 >>>= _, l3 -= _, r2.back += _, 64 & g) {
                e3.msg = "invalid distance code", r2.mode = 30;
                break;
              }
              r2.offset = b, r2.extra = 15 & g, r2.mode = 24;
            case 24:
              if (r2.extra) {
                for (z2 = r2.extra; l3 < z2; ) {
                  if (0 === o2) break e;
                  o2--, u2 += n3[s3++] << l3, l3 += 8;
                }
                r2.offset += u2 & (1 << r2.extra) - 1, u2 >>>= r2.extra, l3 -= r2.extra, r2.back += r2.extra;
              }
              if (r2.offset > r2.dmax) {
                e3.msg = "invalid distance too far back", r2.mode = 30;
                break;
              }
              r2.mode = 25;
            case 25:
              if (0 === h2) break e;
              if (d = c2 - h2, r2.offset > d) {
                if ((d = r2.offset - d) > r2.whave && r2.sane) {
                  e3.msg = "invalid distance too far back", r2.mode = 30;
                  break;
                }
                p = d > r2.wnext ? (d -= r2.wnext, r2.wsize - d) : r2.wnext - d, d > r2.length && (d = r2.length), m = r2.window;
              } else m = i2, p = a2 - r2.offset, d = r2.length;
              for (h2 < d && (d = h2), h2 -= d, r2.length -= d; i2[a2++] = m[p++], --d; ) ;
              0 === r2.length && (r2.mode = 21);
              break;
            case 26:
              if (0 === h2) break e;
              i2[a2++] = r2.length, h2--, r2.mode = 21;
              break;
            case 27:
              if (r2.wrap) {
                for (; l3 < 32; ) {
                  if (0 === o2) break e;
                  o2--, u2 |= n3[s3++] << l3, l3 += 8;
                }
                if (c2 -= h2, e3.total_out += c2, r2.total += c2, c2 && (e3.adler = r2.check = r2.flags ? B(r2.check, i2, c2, a2 - c2) : O(r2.check, i2, c2, a2 - c2)), c2 = h2, (r2.flags ? u2 : L3(u2)) !== r2.check) {
                  e3.msg = "incorrect data check", r2.mode = 30;
                  break;
                }
                l3 = u2 = 0;
              }
              r2.mode = 28;
            case 28:
              if (r2.wrap && r2.flags) {
                for (; l3 < 32; ) {
                  if (0 === o2) break e;
                  o2--, u2 += n3[s3++] << l3, l3 += 8;
                }
                if (u2 !== (4294967295 & r2.total)) {
                  e3.msg = "incorrect length check", r2.mode = 30;
                  break;
                }
                l3 = u2 = 0;
              }
              r2.mode = 29;
            case 29:
              x2 = 1;
              break e;
            case 30:
              x2 = -3;
              break e;
            case 31:
              return -4;
            case 32:
            default:
              return U;
          }
          return e3.next_out = a2, e3.avail_out = h2, e3.next_in = s3, e3.avail_in = o2, r2.hold = u2, r2.bits = l3, (r2.wsize || c2 !== e3.avail_out && r2.mode < 30 && (r2.mode < 27 || 4 !== t2)) && Z(e3, e3.output, e3.next_out, c2 - e3.avail_out) ? (r2.mode = 31, -4) : (f2 -= e3.avail_in, c2 -= e3.avail_out, e3.total_in += f2, e3.total_out += c2, r2.total += c2, r2.wrap && c2 && (e3.adler = r2.check = r2.flags ? B(r2.check, i2, c2, e3.next_out - c2) : O(r2.check, i2, c2, e3.next_out - c2)), e3.data_type = r2.bits + (r2.last ? 64 : 0) + (12 === r2.mode ? 128 : 0) + (20 === r2.mode || 15 === r2.mode ? 256 : 0), (0 == f2 && 0 === c2 || 4 === t2) && x2 === N && (x2 = -5), x2);
        }, r.inflateEnd = function(e3) {
          if (!e3 || !e3.state) return U;
          var t2 = e3.state;
          return t2.window && (t2.window = null), e3.state = null, N;
        }, r.inflateGetHeader = function(e3, t2) {
          var r2;
          return e3 && e3.state ? 0 == (2 & (r2 = e3.state).wrap) ? U : ((r2.head = t2).done = false, N) : U;
        }, r.inflateSetDictionary = function(e3, t2) {
          var r2, n3 = t2.length;
          return e3 && e3.state ? 0 !== (r2 = e3.state).wrap && 11 !== r2.mode ? U : 11 === r2.mode && O(1, t2, n3, 0) !== r2.check ? -3 : Z(e3, t2, n3, n3) ? (r2.mode = 31, -4) : (r2.havedict = 1, N) : U;
        }, r.inflateInfo = "pako inflate (from Nodeca project)";
      }, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./inffast": 48, "./inftrees": 50 }], 50: [function(e, t, r) {
        "use strict";
        var D = e("../utils/common"), F = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0], N = [16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78], U = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0], P = [16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64];
        t.exports = function(e3, t2, r2, n2, i, s2, a, o) {
          var h, u, l2, f, c, d, p, m, _, g = o.bits, b = 0, v = 0, y2 = 0, w = 0, k = 0, x2 = 0, S = 0, z2 = 0, C = 0, E = 0, A = null, I = 0, O = new D.Buf16(16), B = new D.Buf16(16), R = null, T = 0;
          for (b = 0; b <= 15; b++) O[b] = 0;
          for (v = 0; v < n2; v++) O[t2[r2 + v]]++;
          for (k = g, w = 15; 1 <= w && 0 === O[w]; w--) ;
          if (w < k && (k = w), 0 === w) return i[s2++] = 20971520, i[s2++] = 20971520, o.bits = 1, 0;
          for (y2 = 1; y2 < w && 0 === O[y2]; y2++) ;
          for (k < y2 && (k = y2), b = z2 = 1; b <= 15; b++) if (z2 <<= 1, (z2 -= O[b]) < 0) return -1;
          if (0 < z2 && (0 === e3 || 1 !== w)) return -1;
          for (B[1] = 0, b = 1; b < 15; b++) B[b + 1] = B[b] + O[b];
          for (v = 0; v < n2; v++) 0 !== t2[r2 + v] && (a[B[t2[r2 + v]]++] = v);
          if (d = 0 === e3 ? (A = R = a, 19) : 1 === e3 ? (A = F, I -= 257, R = N, T -= 257, 256) : (A = U, R = P, -1), b = y2, c = s2, S = v = E = 0, l2 = -1, f = (C = 1 << (x2 = k)) - 1, 1 === e3 && 852 < C || 2 === e3 && 592 < C) return 1;
          for (; ; ) {
            for (p = b - S, _ = a[v] < d ? (m = 0, a[v]) : a[v] > d ? (m = R[T + a[v]], A[I + a[v]]) : (m = 96, 0), h = 1 << b - S, y2 = u = 1 << x2; i[c + (E >> S) + (u -= h)] = p << 24 | m << 16 | _ | 0, 0 !== u; ) ;
            for (h = 1 << b - 1; E & h; ) h >>= 1;
            if (0 !== h ? (E &= h - 1, E += h) : E = 0, v++, 0 == --O[b]) {
              if (b === w) break;
              b = t2[r2 + a[v]];
            }
            if (k < b && (E & f) !== l2) {
              for (0 === S && (S = k), c += y2, z2 = 1 << (x2 = b - S); x2 + S < w && !((z2 -= O[x2 + S]) <= 0); ) x2++, z2 <<= 1;
              if (C += 1 << x2, 1 === e3 && 852 < C || 2 === e3 && 592 < C) return 1;
              i[l2 = E & f] = k << 24 | x2 << 16 | c - s2 | 0;
            }
          }
          return 0 !== E && (i[c + E] = b - S << 24 | 64 << 16 | 0), o.bits = k, 0;
        };
      }, { "../utils/common": 41 }], 51: [function(e, t, r) {
        "use strict";
        t.exports = { 2: "need dictionary", 1: "stream end", 0: "", "-1": "file error", "-2": "stream error", "-3": "data error", "-4": "insufficient memory", "-5": "buffer error", "-6": "incompatible version" };
      }, {}], 52: [function(e, t, r) {
        "use strict";
        var i = e("../utils/common"), o = 0, h = 1;
        function n2(e3) {
          for (var t2 = e3.length; 0 <= --t2; ) e3[t2] = 0;
        }
        var s2 = 0, a = 29, u = 256, l2 = u + 1 + a, f = 30, c = 19, _ = 2 * l2 + 1, g = 15, d = 16, p = 7, m = 256, b = 16, v = 17, y2 = 18, w = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0], k = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13], x2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7], S = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], z2 = new Array(2 * (l2 + 2));
        n2(z2);
        var C = new Array(2 * f);
        n2(C);
        var E = new Array(512);
        n2(E);
        var A = new Array(256);
        n2(A);
        var I = new Array(a);
        n2(I);
        var O, B, R, T = new Array(f);
        function D(e3, t2, r2, n3, i2) {
          this.static_tree = e3, this.extra_bits = t2, this.extra_base = r2, this.elems = n3, this.max_length = i2, this.has_stree = e3 && e3.length;
        }
        function F(e3, t2) {
          this.dyn_tree = e3, this.max_code = 0, this.stat_desc = t2;
        }
        function N(e3) {
          return e3 < 256 ? E[e3] : E[256 + (e3 >>> 7)];
        }
        function U(e3, t2) {
          e3.pending_buf[e3.pending++] = 255 & t2, e3.pending_buf[e3.pending++] = t2 >>> 8 & 255;
        }
        function P(e3, t2, r2) {
          e3.bi_valid > d - r2 ? (e3.bi_buf |= t2 << e3.bi_valid & 65535, U(e3, e3.bi_buf), e3.bi_buf = t2 >> d - e3.bi_valid, e3.bi_valid += r2 - d) : (e3.bi_buf |= t2 << e3.bi_valid & 65535, e3.bi_valid += r2);
        }
        function L3(e3, t2, r2) {
          P(e3, r2[2 * t2], r2[2 * t2 + 1]);
        }
        function j(e3, t2) {
          for (var r2 = 0; r2 |= 1 & e3, e3 >>>= 1, r2 <<= 1, 0 < --t2; ) ;
          return r2 >>> 1;
        }
        function Z(e3, t2, r2) {
          var n3, i2, s3 = new Array(g + 1), a2 = 0;
          for (n3 = 1; n3 <= g; n3++) s3[n3] = a2 = a2 + r2[n3 - 1] << 1;
          for (i2 = 0; i2 <= t2; i2++) {
            var o2 = e3[2 * i2 + 1];
            0 !== o2 && (e3[2 * i2] = j(s3[o2]++, o2));
          }
        }
        function W(e3) {
          var t2;
          for (t2 = 0; t2 < l2; t2++) e3.dyn_ltree[2 * t2] = 0;
          for (t2 = 0; t2 < f; t2++) e3.dyn_dtree[2 * t2] = 0;
          for (t2 = 0; t2 < c; t2++) e3.bl_tree[2 * t2] = 0;
          e3.dyn_ltree[2 * m] = 1, e3.opt_len = e3.static_len = 0, e3.last_lit = e3.matches = 0;
        }
        function M(e3) {
          8 < e3.bi_valid ? U(e3, e3.bi_buf) : 0 < e3.bi_valid && (e3.pending_buf[e3.pending++] = e3.bi_buf), e3.bi_buf = 0, e3.bi_valid = 0;
        }
        function H(e3, t2, r2, n3) {
          var i2 = 2 * t2, s3 = 2 * r2;
          return e3[i2] < e3[s3] || e3[i2] === e3[s3] && n3[t2] <= n3[r2];
        }
        function G(e3, t2, r2) {
          for (var n3 = e3.heap[r2], i2 = r2 << 1; i2 <= e3.heap_len && (i2 < e3.heap_len && H(t2, e3.heap[i2 + 1], e3.heap[i2], e3.depth) && i2++, !H(t2, n3, e3.heap[i2], e3.depth)); ) e3.heap[r2] = e3.heap[i2], r2 = i2, i2 <<= 1;
          e3.heap[r2] = n3;
        }
        function K(e3, t2, r2) {
          var n3, i2, s3, a2, o2 = 0;
          if (0 !== e3.last_lit) for (; n3 = e3.pending_buf[e3.d_buf + 2 * o2] << 8 | e3.pending_buf[e3.d_buf + 2 * o2 + 1], i2 = e3.pending_buf[e3.l_buf + o2], o2++, 0 === n3 ? L3(e3, i2, t2) : (L3(e3, (s3 = A[i2]) + u + 1, t2), 0 !== (a2 = w[s3]) && P(e3, i2 -= I[s3], a2), L3(e3, s3 = N(--n3), r2), 0 !== (a2 = k[s3]) && P(e3, n3 -= T[s3], a2)), o2 < e3.last_lit; ) ;
          L3(e3, m, t2);
        }
        function Y(e3, t2) {
          var r2, n3, i2, s3 = t2.dyn_tree, a2 = t2.stat_desc.static_tree, o2 = t2.stat_desc.has_stree, h2 = t2.stat_desc.elems, u2 = -1;
          for (e3.heap_len = 0, e3.heap_max = _, r2 = 0; r2 < h2; r2++) 0 !== s3[2 * r2] ? (e3.heap[++e3.heap_len] = u2 = r2, e3.depth[r2] = 0) : s3[2 * r2 + 1] = 0;
          for (; e3.heap_len < 2; ) s3[2 * (i2 = e3.heap[++e3.heap_len] = u2 < 2 ? ++u2 : 0)] = 1, e3.depth[i2] = 0, e3.opt_len--, o2 && (e3.static_len -= a2[2 * i2 + 1]);
          for (t2.max_code = u2, r2 = e3.heap_len >> 1; 1 <= r2; r2--) G(e3, s3, r2);
          for (i2 = h2; r2 = e3.heap[1], e3.heap[1] = e3.heap[e3.heap_len--], G(e3, s3, 1), n3 = e3.heap[1], e3.heap[--e3.heap_max] = r2, e3.heap[--e3.heap_max] = n3, s3[2 * i2] = s3[2 * r2] + s3[2 * n3], e3.depth[i2] = (e3.depth[r2] >= e3.depth[n3] ? e3.depth[r2] : e3.depth[n3]) + 1, s3[2 * r2 + 1] = s3[2 * n3 + 1] = i2, e3.heap[1] = i2++, G(e3, s3, 1), 2 <= e3.heap_len; ) ;
          e3.heap[--e3.heap_max] = e3.heap[1], (function(e4, t3) {
            var r3, n4, i3, s4, a3, o3, h3 = t3.dyn_tree, u3 = t3.max_code, l3 = t3.stat_desc.static_tree, f2 = t3.stat_desc.has_stree, c2 = t3.stat_desc.extra_bits, d2 = t3.stat_desc.extra_base, p2 = t3.stat_desc.max_length, m2 = 0;
            for (s4 = 0; s4 <= g; s4++) e4.bl_count[s4] = 0;
            for (h3[2 * e4.heap[e4.heap_max] + 1] = 0, r3 = e4.heap_max + 1; r3 < _; r3++) p2 < (s4 = h3[2 * h3[2 * (n4 = e4.heap[r3]) + 1] + 1] + 1) && (s4 = p2, m2++), h3[2 * n4 + 1] = s4, u3 < n4 || (e4.bl_count[s4]++, a3 = 0, d2 <= n4 && (a3 = c2[n4 - d2]), o3 = h3[2 * n4], e4.opt_len += o3 * (s4 + a3), f2 && (e4.static_len += o3 * (l3[2 * n4 + 1] + a3)));
            if (0 !== m2) {
              do {
                for (s4 = p2 - 1; 0 === e4.bl_count[s4]; ) s4--;
                e4.bl_count[s4]--, e4.bl_count[s4 + 1] += 2, e4.bl_count[p2]--, m2 -= 2;
              } while (0 < m2);
              for (s4 = p2; 0 !== s4; s4--) for (n4 = e4.bl_count[s4]; 0 !== n4; ) u3 < (i3 = e4.heap[--r3]) || (h3[2 * i3 + 1] !== s4 && (e4.opt_len += (s4 - h3[2 * i3 + 1]) * h3[2 * i3], h3[2 * i3 + 1] = s4), n4--);
            }
          })(e3, t2), Z(s3, u2, e3.bl_count);
        }
        function X(e3, t2, r2) {
          var n3, i2, s3 = -1, a2 = t2[1], o2 = 0, h2 = 7, u2 = 4;
          for (0 === a2 && (h2 = 138, u2 = 3), t2[2 * (r2 + 1) + 1] = 65535, n3 = 0; n3 <= r2; n3++) i2 = a2, a2 = t2[2 * (n3 + 1) + 1], ++o2 < h2 && i2 === a2 || (o2 < u2 ? e3.bl_tree[2 * i2] += o2 : 0 !== i2 ? (i2 !== s3 && e3.bl_tree[2 * i2]++, e3.bl_tree[2 * b]++) : o2 <= 10 ? e3.bl_tree[2 * v]++ : e3.bl_tree[2 * y2]++, s3 = i2, u2 = (o2 = 0) === a2 ? (h2 = 138, 3) : i2 === a2 ? (h2 = 6, 3) : (h2 = 7, 4));
        }
        function V(e3, t2, r2) {
          var n3, i2, s3 = -1, a2 = t2[1], o2 = 0, h2 = 7, u2 = 4;
          for (0 === a2 && (h2 = 138, u2 = 3), n3 = 0; n3 <= r2; n3++) if (i2 = a2, a2 = t2[2 * (n3 + 1) + 1], !(++o2 < h2 && i2 === a2)) {
            if (o2 < u2) for (; L3(e3, i2, e3.bl_tree), 0 != --o2; ) ;
            else 0 !== i2 ? (i2 !== s3 && (L3(e3, i2, e3.bl_tree), o2--), L3(e3, b, e3.bl_tree), P(e3, o2 - 3, 2)) : o2 <= 10 ? (L3(e3, v, e3.bl_tree), P(e3, o2 - 3, 3)) : (L3(e3, y2, e3.bl_tree), P(e3, o2 - 11, 7));
            s3 = i2, u2 = (o2 = 0) === a2 ? (h2 = 138, 3) : i2 === a2 ? (h2 = 6, 3) : (h2 = 7, 4);
          }
        }
        n2(T);
        var q = false;
        function J(e3, t2, r2, n3) {
          P(e3, (s2 << 1) + (n3 ? 1 : 0), 3), (function(e4, t3, r3, n4) {
            M(e4), n4 && (U(e4, r3), U(e4, ~r3)), i.arraySet(e4.pending_buf, e4.window, t3, r3, e4.pending), e4.pending += r3;
          })(e3, t2, r2, true);
        }
        r._tr_init = function(e3) {
          q || ((function() {
            var e4, t2, r2, n3, i2, s3 = new Array(g + 1);
            for (n3 = r2 = 0; n3 < a - 1; n3++) for (I[n3] = r2, e4 = 0; e4 < 1 << w[n3]; e4++) A[r2++] = n3;
            for (A[r2 - 1] = n3, n3 = i2 = 0; n3 < 16; n3++) for (T[n3] = i2, e4 = 0; e4 < 1 << k[n3]; e4++) E[i2++] = n3;
            for (i2 >>= 7; n3 < f; n3++) for (T[n3] = i2 << 7, e4 = 0; e4 < 1 << k[n3] - 7; e4++) E[256 + i2++] = n3;
            for (t2 = 0; t2 <= g; t2++) s3[t2] = 0;
            for (e4 = 0; e4 <= 143; ) z2[2 * e4 + 1] = 8, e4++, s3[8]++;
            for (; e4 <= 255; ) z2[2 * e4 + 1] = 9, e4++, s3[9]++;
            for (; e4 <= 279; ) z2[2 * e4 + 1] = 7, e4++, s3[7]++;
            for (; e4 <= 287; ) z2[2 * e4 + 1] = 8, e4++, s3[8]++;
            for (Z(z2, l2 + 1, s3), e4 = 0; e4 < f; e4++) C[2 * e4 + 1] = 5, C[2 * e4] = j(e4, 5);
            O = new D(z2, w, u + 1, l2, g), B = new D(C, k, 0, f, g), R = new D(new Array(0), x2, 0, c, p);
          })(), q = true), e3.l_desc = new F(e3.dyn_ltree, O), e3.d_desc = new F(e3.dyn_dtree, B), e3.bl_desc = new F(e3.bl_tree, R), e3.bi_buf = 0, e3.bi_valid = 0, W(e3);
        }, r._tr_stored_block = J, r._tr_flush_block = function(e3, t2, r2, n3) {
          var i2, s3, a2 = 0;
          0 < e3.level ? (2 === e3.strm.data_type && (e3.strm.data_type = (function(e4) {
            var t3, r3 = 4093624447;
            for (t3 = 0; t3 <= 31; t3++, r3 >>>= 1) if (1 & r3 && 0 !== e4.dyn_ltree[2 * t3]) return o;
            if (0 !== e4.dyn_ltree[18] || 0 !== e4.dyn_ltree[20] || 0 !== e4.dyn_ltree[26]) return h;
            for (t3 = 32; t3 < u; t3++) if (0 !== e4.dyn_ltree[2 * t3]) return h;
            return o;
          })(e3)), Y(e3, e3.l_desc), Y(e3, e3.d_desc), a2 = (function(e4) {
            var t3;
            for (X(e4, e4.dyn_ltree, e4.l_desc.max_code), X(e4, e4.dyn_dtree, e4.d_desc.max_code), Y(e4, e4.bl_desc), t3 = c - 1; 3 <= t3 && 0 === e4.bl_tree[2 * S[t3] + 1]; t3--) ;
            return e4.opt_len += 3 * (t3 + 1) + 5 + 5 + 4, t3;
          })(e3), i2 = e3.opt_len + 3 + 7 >>> 3, (s3 = e3.static_len + 3 + 7 >>> 3) <= i2 && (i2 = s3)) : i2 = s3 = r2 + 5, r2 + 4 <= i2 && -1 !== t2 ? J(e3, t2, r2, n3) : 4 === e3.strategy || s3 === i2 ? (P(e3, 2 + (n3 ? 1 : 0), 3), K(e3, z2, C)) : (P(e3, 4 + (n3 ? 1 : 0), 3), (function(e4, t3, r3, n4) {
            var i3;
            for (P(e4, t3 - 257, 5), P(e4, r3 - 1, 5), P(e4, n4 - 4, 4), i3 = 0; i3 < n4; i3++) P(e4, e4.bl_tree[2 * S[i3] + 1], 3);
            V(e4, e4.dyn_ltree, t3 - 1), V(e4, e4.dyn_dtree, r3 - 1);
          })(e3, e3.l_desc.max_code + 1, e3.d_desc.max_code + 1, a2 + 1), K(e3, e3.dyn_ltree, e3.dyn_dtree)), W(e3), n3 && M(e3);
        }, r._tr_tally = function(e3, t2, r2) {
          return e3.pending_buf[e3.d_buf + 2 * e3.last_lit] = t2 >>> 8 & 255, e3.pending_buf[e3.d_buf + 2 * e3.last_lit + 1] = 255 & t2, e3.pending_buf[e3.l_buf + e3.last_lit] = 255 & r2, e3.last_lit++, 0 === t2 ? e3.dyn_ltree[2 * r2]++ : (e3.matches++, t2--, e3.dyn_ltree[2 * (A[r2] + u + 1)]++, e3.dyn_dtree[2 * N(t2)]++), e3.last_lit === e3.lit_bufsize - 1;
        }, r._tr_align = function(e3) {
          P(e3, 2, 3), L3(e3, m, z2), (function(e4) {
            16 === e4.bi_valid ? (U(e4, e4.bi_buf), e4.bi_buf = 0, e4.bi_valid = 0) : 8 <= e4.bi_valid && (e4.pending_buf[e4.pending++] = 255 & e4.bi_buf, e4.bi_buf >>= 8, e4.bi_valid -= 8);
          })(e3);
        };
      }, { "../utils/common": 41 }], 53: [function(e, t, r) {
        "use strict";
        t.exports = function() {
          this.input = null, this.next_in = 0, this.avail_in = 0, this.total_in = 0, this.output = null, this.next_out = 0, this.avail_out = 0, this.total_out = 0, this.msg = "", this.state = null, this.data_type = 2, this.adler = 0;
        };
      }, {}], 54: [function(e, t, r) {
        (function(e3) {
          !(function(r2, n2) {
            "use strict";
            if (!r2.setImmediate) {
              var i, s2, t2, a, o = 1, h = {}, u = false, l2 = r2.document, e4 = Object.getPrototypeOf && Object.getPrototypeOf(r2);
              e4 = e4 && e4.setTimeout ? e4 : r2, i = "[object process]" === {}.toString.call(r2.process) ? function(e6) {
                process.nextTick(function() {
                  c(e6);
                });
              } : (function() {
                if (r2.postMessage && !r2.importScripts) {
                  var e6 = true, t3 = r2.onmessage;
                  return r2.onmessage = function() {
                    e6 = false;
                  }, r2.postMessage("", "*"), r2.onmessage = t3, e6;
                }
              })() ? (a = "setImmediate$" + Math.random() + "$", r2.addEventListener ? r2.addEventListener("message", d, false) : r2.attachEvent("onmessage", d), function(e6) {
                r2.postMessage(a + e6, "*");
              }) : r2.MessageChannel ? ((t2 = new MessageChannel()).port1.onmessage = function(e6) {
                c(e6.data);
              }, function(e6) {
                t2.port2.postMessage(e6);
              }) : l2 && "onreadystatechange" in l2.createElement("script") ? (s2 = l2.documentElement, function(e6) {
                var t3 = l2.createElement("script");
                t3.onreadystatechange = function() {
                  c(e6), t3.onreadystatechange = null, s2.removeChild(t3), t3 = null;
                }, s2.appendChild(t3);
              }) : function(e6) {
                setTimeout(c, 0, e6);
              }, e4.setImmediate = function(e6) {
                "function" != typeof e6 && (e6 = new Function("" + e6));
                for (var t3 = new Array(arguments.length - 1), r3 = 0; r3 < t3.length; r3++) t3[r3] = arguments[r3 + 1];
                var n3 = { callback: e6, args: t3 };
                return h[o] = n3, i(o), o++;
              }, e4.clearImmediate = f;
            }
            function f(e6) {
              delete h[e6];
            }
            function c(e6) {
              if (u) setTimeout(c, 0, e6);
              else {
                var t3 = h[e6];
                if (t3) {
                  u = true;
                  try {
                    !(function(e7) {
                      var t4 = e7.callback, r3 = e7.args;
                      switch (r3.length) {
                        case 0:
                          t4();
                          break;
                        case 1:
                          t4(r3[0]);
                          break;
                        case 2:
                          t4(r3[0], r3[1]);
                          break;
                        case 3:
                          t4(r3[0], r3[1], r3[2]);
                          break;
                        default:
                          t4.apply(n2, r3);
                      }
                    })(t3);
                  } finally {
                    f(e6), u = false;
                  }
                }
              }
            }
            function d(e6) {
              e6.source === r2 && "string" == typeof e6.data && 0 === e6.data.indexOf(a) && c(+e6.data.slice(a.length));
            }
          })("undefined" == typeof self ? void 0 === e3 ? this : e3 : self);
        }).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
      }, {}] }, {}, [10])(10);
    });
  }
});

// src/animatedseismograph.mts
var animatedseismograph_exports = {};
__export(animatedseismograph_exports, {
  AnimatedTimeScaler: () => AnimatedTimeScaler,
  RTDisplayContainer: () => RTDisplayContainer,
  calcOnePixelDuration: () => calcOnePixelDuration,
  createRealtimeDisplay: () => createRealtimeDisplay,
  internalCreateRealtimeDisplay: () => internalCreateRealtimeDisplay,
  isValidRTConfig: () => isValidRTConfig,
  trim: () => trim
});

// node_modules/luxon/build/es6/luxon.mjs
var luxon_exports = {};
__export(luxon_exports, {
  DateTime: () => DateTime,
  Duration: () => Duration,
  FixedOffsetZone: () => FixedOffsetZone,
  IANAZone: () => IANAZone,
  Info: () => Info,
  Interval: () => Interval,
  InvalidZone: () => InvalidZone,
  Settings: () => Settings,
  SystemZone: () => SystemZone,
  VERSION: () => VERSION,
  Zone: () => Zone
});
var LuxonError = class extends Error {
};
var InvalidDateTimeError = class extends LuxonError {
  constructor(reason) {
    super(`Invalid DateTime: ${reason.toMessage()}`);
  }
};
var InvalidIntervalError = class extends LuxonError {
  constructor(reason) {
    super(`Invalid Interval: ${reason.toMessage()}`);
  }
};
var InvalidDurationError = class extends LuxonError {
  constructor(reason) {
    super(`Invalid Duration: ${reason.toMessage()}`);
  }
};
var ConflictingSpecificationError = class extends LuxonError {
};
var InvalidUnitError = class extends LuxonError {
  constructor(unit3) {
    super(`Invalid unit ${unit3}`);
  }
};
var InvalidArgumentError = class extends LuxonError {
};
var ZoneIsAbstractError = class extends LuxonError {
  constructor() {
    super("Zone is an abstract class");
  }
};
var n = "numeric";
var s = "short";
var l = "long";
var DATE_SHORT = {
  year: n,
  month: n,
  day: n
};
var DATE_MED = {
  year: n,
  month: s,
  day: n
};
var DATE_MED_WITH_WEEKDAY = {
  year: n,
  month: s,
  day: n,
  weekday: s
};
var DATE_FULL = {
  year: n,
  month: l,
  day: n
};
var DATE_HUGE = {
  year: n,
  month: l,
  day: n,
  weekday: l
};
var TIME_SIMPLE = {
  hour: n,
  minute: n
};
var TIME_WITH_SECONDS = {
  hour: n,
  minute: n,
  second: n
};
var TIME_WITH_SHORT_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  timeZoneName: s
};
var TIME_WITH_LONG_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  timeZoneName: l
};
var TIME_24_SIMPLE = {
  hour: n,
  minute: n,
  hourCycle: "h23"
};
var TIME_24_WITH_SECONDS = {
  hour: n,
  minute: n,
  second: n,
  hourCycle: "h23"
};
var TIME_24_WITH_SHORT_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  hourCycle: "h23",
  timeZoneName: s
};
var TIME_24_WITH_LONG_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  hourCycle: "h23",
  timeZoneName: l
};
var DATETIME_SHORT = {
  year: n,
  month: n,
  day: n,
  hour: n,
  minute: n
};
var DATETIME_SHORT_WITH_SECONDS = {
  year: n,
  month: n,
  day: n,
  hour: n,
  minute: n,
  second: n
};
var DATETIME_MED = {
  year: n,
  month: s,
  day: n,
  hour: n,
  minute: n
};
var DATETIME_MED_WITH_SECONDS = {
  year: n,
  month: s,
  day: n,
  hour: n,
  minute: n,
  second: n
};
var DATETIME_MED_WITH_WEEKDAY = {
  year: n,
  month: s,
  day: n,
  weekday: s,
  hour: n,
  minute: n
};
var DATETIME_FULL = {
  year: n,
  month: l,
  day: n,
  hour: n,
  minute: n,
  timeZoneName: s
};
var DATETIME_FULL_WITH_SECONDS = {
  year: n,
  month: l,
  day: n,
  hour: n,
  minute: n,
  second: n,
  timeZoneName: s
};
var DATETIME_HUGE = {
  year: n,
  month: l,
  day: n,
  weekday: l,
  hour: n,
  minute: n,
  timeZoneName: l
};
var DATETIME_HUGE_WITH_SECONDS = {
  year: n,
  month: l,
  day: n,
  weekday: l,
  hour: n,
  minute: n,
  second: n,
  timeZoneName: l
};
var Zone = class {
  /**
   * The type of zone
   * @abstract
   * @type {string}
   */
  get type() {
    throw new ZoneIsAbstractError();
  }
  /**
   * The name of this zone.
   * @abstract
   * @type {string}
   */
  get name() {
    throw new ZoneIsAbstractError();
  }
  /**
   * The IANA name of this zone.
   * Defaults to `name` if not overwritten by a subclass.
   * @abstract
   * @type {string}
   */
  get ianaName() {
    return this.name;
  }
  /**
   * Returns whether the offset is known to be fixed for the whole year.
   * @abstract
   * @type {boolean}
   */
  get isUniversal() {
    throw new ZoneIsAbstractError();
  }
  /**
   * Returns the offset's common name (such as EST) at the specified timestamp
   * @abstract
   * @param {number} ts - Epoch milliseconds for which to get the name
   * @param {Object} opts - Options to affect the format
   * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
   * @param {string} opts.locale - What locale to return the offset name in.
   * @return {string}
   */
  offsetName(ts, opts) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Returns the offset's value as a string
   * @abstract
   * @param {number} ts - Epoch milliseconds for which to get the offset
   * @param {string} format - What style of offset to return.
   *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
   * @return {string}
   */
  formatOffset(ts, format2) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Return the offset in minutes for this zone at the specified timestamp.
   * @abstract
   * @param {number} ts - Epoch milliseconds for which to compute the offset
   * @return {number}
   */
  offset(ts) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Return whether this Zone is equal to another zone
   * @abstract
   * @param {Zone} otherZone - the zone to compare
   * @return {boolean}
   */
  equals(otherZone) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Return whether this Zone is valid.
   * @abstract
   * @type {boolean}
   */
  get isValid() {
    throw new ZoneIsAbstractError();
  }
};
var singleton$1 = null;
var SystemZone = class _SystemZone extends Zone {
  /**
   * Get a singleton instance of the local zone
   * @return {SystemZone}
   */
  static get instance() {
    if (singleton$1 === null) {
      singleton$1 = new _SystemZone();
    }
    return singleton$1;
  }
  /** @override **/
  get type() {
    return "system";
  }
  /** @override **/
  get name() {
    return new Intl.DateTimeFormat().resolvedOptions().timeZone;
  }
  /** @override **/
  get isUniversal() {
    return false;
  }
  /** @override **/
  offsetName(ts, { format: format2, locale: locale3 }) {
    return parseZoneInfo(ts, format2, locale3);
  }
  /** @override **/
  formatOffset(ts, format2) {
    return formatOffset(this.offset(ts), format2);
  }
  /** @override **/
  offset(ts) {
    return -new Date(ts).getTimezoneOffset();
  }
  /** @override **/
  equals(otherZone) {
    return otherZone.type === "system";
  }
  /** @override **/
  get isValid() {
    return true;
  }
};
var dtfCache = /* @__PURE__ */ new Map();
function makeDTF(zoneName) {
  let dtf = dtfCache.get(zoneName);
  if (dtf === void 0) {
    dtf = new Intl.DateTimeFormat("en-US", {
      hour12: false,
      timeZone: zoneName,
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      era: "short"
    });
    dtfCache.set(zoneName, dtf);
  }
  return dtf;
}
var typeToPos = {
  year: 0,
  month: 1,
  day: 2,
  era: 3,
  hour: 4,
  minute: 5,
  second: 6
};
function hackyOffset(dtf, date6) {
  const formatted = dtf.format(date6).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;
  return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];
}
function partsOffset(dtf, date6) {
  const formatted = dtf.formatToParts(date6);
  const filled = [];
  for (let i = 0; i < formatted.length; i++) {
    const { type, value } = formatted[i];
    const pos = typeToPos[type];
    if (type === "era") {
      filled[pos] = value;
    } else if (!isUndefined(pos)) {
      filled[pos] = parseInt(value, 10);
    }
  }
  return filled;
}
var ianaZoneCache = /* @__PURE__ */ new Map();
var IANAZone = class _IANAZone extends Zone {
  /**
   * @param {string} name - Zone name
   * @return {IANAZone}
   */
  static create(name) {
    let zone = ianaZoneCache.get(name);
    if (zone === void 0) {
      ianaZoneCache.set(name, zone = new _IANAZone(name));
    }
    return zone;
  }
  /**
   * Reset local caches. Should only be necessary in testing scenarios.
   * @return {void}
   */
  static resetCache() {
    ianaZoneCache.clear();
    dtfCache.clear();
  }
  /**
   * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.
   * @param {string} s - The string to check validity on
   * @example IANAZone.isValidSpecifier("America/New_York") //=> true
   * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false
   * @deprecated For backward compatibility, this forwards to isValidZone, better use `isValidZone()` directly instead.
   * @return {boolean}
   */
  static isValidSpecifier(s2) {
    return this.isValidZone(s2);
  }
  /**
   * Returns whether the provided string identifies a real zone
   * @param {string} zone - The string to check
   * @example IANAZone.isValidZone("America/New_York") //=> true
   * @example IANAZone.isValidZone("Fantasia/Castle") //=> false
   * @example IANAZone.isValidZone("Sport~~blorp") //=> false
   * @return {boolean}
   */
  static isValidZone(zone) {
    if (!zone) {
      return false;
    }
    try {
      new Intl.DateTimeFormat("en-US", { timeZone: zone }).format();
      return true;
    } catch (e) {
      return false;
    }
  }
  constructor(name) {
    super();
    this.zoneName = name;
    this.valid = _IANAZone.isValidZone(name);
  }
  /**
   * The type of zone. `iana` for all instances of `IANAZone`.
   * @override
   * @type {string}
   */
  get type() {
    return "iana";
  }
  /**
   * The name of this zone (i.e. the IANA zone name).
   * @override
   * @type {string}
   */
  get name() {
    return this.zoneName;
  }
  /**
   * Returns whether the offset is known to be fixed for the whole year:
   * Always returns false for all IANA zones.
   * @override
   * @type {boolean}
   */
  get isUniversal() {
    return false;
  }
  /**
   * Returns the offset's common name (such as EST) at the specified timestamp
   * @override
   * @param {number} ts - Epoch milliseconds for which to get the name
   * @param {Object} opts - Options to affect the format
   * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
   * @param {string} opts.locale - What locale to return the offset name in.
   * @return {string}
   */
  offsetName(ts, { format: format2, locale: locale3 }) {
    return parseZoneInfo(ts, format2, locale3, this.name);
  }
  /**
   * Returns the offset's value as a string
   * @override
   * @param {number} ts - Epoch milliseconds for which to get the offset
   * @param {string} format - What style of offset to return.
   *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
   * @return {string}
   */
  formatOffset(ts, format2) {
    return formatOffset(this.offset(ts), format2);
  }
  /**
   * Return the offset in minutes for this zone at the specified timestamp.
   * @override
   * @param {number} ts - Epoch milliseconds for which to compute the offset
   * @return {number}
   */
  offset(ts) {
    if (!this.valid) return NaN;
    const date6 = new Date(ts);
    if (isNaN(date6)) return NaN;
    const dtf = makeDTF(this.name);
    let [year, month, day, adOrBc, hour, minute, second2] = dtf.formatToParts ? partsOffset(dtf, date6) : hackyOffset(dtf, date6);
    if (adOrBc === "BC") {
      year = -Math.abs(year) + 1;
    }
    const adjustedHour = hour === 24 ? 0 : hour;
    const asUTC = objToLocalTS({
      year,
      month,
      day,
      hour: adjustedHour,
      minute,
      second: second2,
      millisecond: 0
    });
    let asTS = +date6;
    const over = asTS % 1e3;
    asTS -= over >= 0 ? over : 1e3 + over;
    return (asUTC - asTS) / (60 * 1e3);
  }
  /**
   * Return whether this Zone is equal to another zone
   * @override
   * @param {Zone} otherZone - the zone to compare
   * @return {boolean}
   */
  equals(otherZone) {
    return otherZone.type === "iana" && otherZone.name === this.name;
  }
  /**
   * Return whether this Zone is valid.
   * @override
   * @type {boolean}
   */
  get isValid() {
    return this.valid;
  }
};
var intlLFCache = {};
function getCachedLF(locString, opts = {}) {
  const key = JSON.stringify([locString, opts]);
  let dtf = intlLFCache[key];
  if (!dtf) {
    dtf = new Intl.ListFormat(locString, opts);
    intlLFCache[key] = dtf;
  }
  return dtf;
}
var intlDTCache = /* @__PURE__ */ new Map();
function getCachedDTF(locString, opts = {}) {
  const key = JSON.stringify([locString, opts]);
  let dtf = intlDTCache.get(key);
  if (dtf === void 0) {
    dtf = new Intl.DateTimeFormat(locString, opts);
    intlDTCache.set(key, dtf);
  }
  return dtf;
}
var intlNumCache = /* @__PURE__ */ new Map();
function getCachedINF(locString, opts = {}) {
  const key = JSON.stringify([locString, opts]);
  let inf = intlNumCache.get(key);
  if (inf === void 0) {
    inf = new Intl.NumberFormat(locString, opts);
    intlNumCache.set(key, inf);
  }
  return inf;
}
var intlRelCache = /* @__PURE__ */ new Map();
function getCachedRTF(locString, opts = {}) {
  const { base, ...cacheKeyOpts } = opts;
  const key = JSON.stringify([locString, cacheKeyOpts]);
  let inf = intlRelCache.get(key);
  if (inf === void 0) {
    inf = new Intl.RelativeTimeFormat(locString, opts);
    intlRelCache.set(key, inf);
  }
  return inf;
}
var sysLocaleCache = null;
function systemLocale() {
  if (sysLocaleCache) {
    return sysLocaleCache;
  } else {
    sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;
    return sysLocaleCache;
  }
}
var intlResolvedOptionsCache = /* @__PURE__ */ new Map();
function getCachedIntResolvedOptions(locString) {
  let opts = intlResolvedOptionsCache.get(locString);
  if (opts === void 0) {
    opts = new Intl.DateTimeFormat(locString).resolvedOptions();
    intlResolvedOptionsCache.set(locString, opts);
  }
  return opts;
}
var weekInfoCache = /* @__PURE__ */ new Map();
function getCachedWeekInfo(locString) {
  let data = weekInfoCache.get(locString);
  if (!data) {
    const locale3 = new Intl.Locale(locString);
    data = "getWeekInfo" in locale3 ? locale3.getWeekInfo() : locale3.weekInfo;
    if (!("minimalDays" in data)) {
      data = { ...fallbackWeekSettings, ...data };
    }
    weekInfoCache.set(locString, data);
  }
  return data;
}
function parseLocaleString(localeStr) {
  const xIndex = localeStr.indexOf("-x-");
  if (xIndex !== -1) {
    localeStr = localeStr.substring(0, xIndex);
  }
  const uIndex = localeStr.indexOf("-u-");
  if (uIndex === -1) {
    return [localeStr];
  } else {
    let options;
    let selectedStr;
    try {
      options = getCachedDTF(localeStr).resolvedOptions();
      selectedStr = localeStr;
    } catch (e) {
      const smaller = localeStr.substring(0, uIndex);
      options = getCachedDTF(smaller).resolvedOptions();
      selectedStr = smaller;
    }
    const { numberingSystem, calendar: calendar2 } = options;
    return [selectedStr, numberingSystem, calendar2];
  }
}
function intlConfigString(localeStr, numberingSystem, outputCalendar) {
  if (outputCalendar || numberingSystem) {
    if (!localeStr.includes("-u-")) {
      localeStr += "-u";
    }
    if (outputCalendar) {
      localeStr += `-ca-${outputCalendar}`;
    }
    if (numberingSystem) {
      localeStr += `-nu-${numberingSystem}`;
    }
    return localeStr;
  } else {
    return localeStr;
  }
}
function mapMonths(f) {
  const ms = [];
  for (let i = 1; i <= 12; i++) {
    const dt = DateTime.utc(2009, i, 1);
    ms.push(f(dt));
  }
  return ms;
}
function mapWeekdays(f) {
  const ms = [];
  for (let i = 1; i <= 7; i++) {
    const dt = DateTime.utc(2016, 11, 13 + i);
    ms.push(f(dt));
  }
  return ms;
}
function listStuff(loc, length, englishFn, intlFn) {
  const mode = loc.listingMode();
  if (mode === "error") {
    return null;
  } else if (mode === "en") {
    return englishFn(length);
  } else {
    return intlFn(length);
  }
}
function supportsFastNumbers(loc) {
  if (loc.numberingSystem && loc.numberingSystem !== "latn") {
    return false;
  } else {
    return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || getCachedIntResolvedOptions(loc.locale).numberingSystem === "latn";
  }
}
var PolyNumberFormatter = class {
  constructor(intl, forceSimple, opts) {
    this.padTo = opts.padTo || 0;
    this.floor = opts.floor || false;
    const { padTo, floor, ...otherOpts } = opts;
    if (!forceSimple || Object.keys(otherOpts).length > 0) {
      const intlOpts = { useGrouping: false, ...opts };
      if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;
      this.inf = getCachedINF(intl, intlOpts);
    }
  }
  format(i) {
    if (this.inf) {
      const fixed = this.floor ? Math.floor(i) : i;
      return this.inf.format(fixed);
    } else {
      const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);
      return padStart(fixed, this.padTo);
    }
  }
};
var PolyDateFormatter = class {
  constructor(dt, intl, opts) {
    this.opts = opts;
    this.originalZone = void 0;
    let z2 = void 0;
    if (this.opts.timeZone) {
      this.dt = dt;
    } else if (dt.zone.type === "fixed") {
      const gmtOffset = -1 * (dt.offset / 60);
      const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;
      if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {
        z2 = offsetZ;
        this.dt = dt;
      } else {
        z2 = "UTC";
        this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({ minutes: dt.offset });
        this.originalZone = dt.zone;
      }
    } else if (dt.zone.type === "system") {
      this.dt = dt;
    } else if (dt.zone.type === "iana") {
      this.dt = dt;
      z2 = dt.zone.name;
    } else {
      z2 = "UTC";
      this.dt = dt.setZone("UTC").plus({ minutes: dt.offset });
      this.originalZone = dt.zone;
    }
    const intlOpts = { ...this.opts };
    intlOpts.timeZone = intlOpts.timeZone || z2;
    this.dtf = getCachedDTF(intl, intlOpts);
  }
  format() {
    if (this.originalZone) {
      return this.formatToParts().map(({ value }) => value).join("");
    }
    return this.dtf.format(this.dt.toJSDate());
  }
  formatToParts() {
    const parts = this.dtf.formatToParts(this.dt.toJSDate());
    if (this.originalZone) {
      return parts.map((part) => {
        if (part.type === "timeZoneName") {
          const offsetName = this.originalZone.offsetName(this.dt.ts, {
            locale: this.dt.locale,
            format: this.opts.timeZoneName
          });
          return {
            ...part,
            value: offsetName
          };
        } else {
          return part;
        }
      });
    }
    return parts;
  }
  resolvedOptions() {
    return this.dtf.resolvedOptions();
  }
};
var PolyRelFormatter = class {
  constructor(intl, isEnglish, opts) {
    this.opts = { style: "long", ...opts };
    if (!isEnglish && hasRelative()) {
      this.rtf = getCachedRTF(intl, opts);
    }
  }
  format(count, unit3) {
    if (this.rtf) {
      return this.rtf.format(count, unit3);
    } else {
      return formatRelativeTime(unit3, count, this.opts.numeric, this.opts.style !== "long");
    }
  }
  formatToParts(count, unit3) {
    if (this.rtf) {
      return this.rtf.formatToParts(count, unit3);
    } else {
      return [];
    }
  }
};
var fallbackWeekSettings = {
  firstDay: 1,
  minimalDays: 4,
  weekend: [6, 7]
};
var Locale = class _Locale {
  static fromOpts(opts) {
    return _Locale.create(
      opts.locale,
      opts.numberingSystem,
      opts.outputCalendar,
      opts.weekSettings,
      opts.defaultToEN
    );
  }
  static create(locale3, numberingSystem, outputCalendar, weekSettings, defaultToEN = false) {
    const specifiedLocale = locale3 || Settings.defaultLocale;
    const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale());
    const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;
    const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;
    const weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings;
    return new _Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale);
  }
  static resetCache() {
    sysLocaleCache = null;
    intlDTCache.clear();
    intlNumCache.clear();
    intlRelCache.clear();
    intlResolvedOptionsCache.clear();
    weekInfoCache.clear();
  }
  static fromObject({ locale: locale3, numberingSystem, outputCalendar, weekSettings } = {}) {
    return _Locale.create(locale3, numberingSystem, outputCalendar, weekSettings);
  }
  constructor(locale3, numbering, outputCalendar, weekSettings, specifiedLocale) {
    const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale3);
    this.locale = parsedLocale;
    this.numberingSystem = numbering || parsedNumberingSystem || null;
    this.outputCalendar = outputCalendar || parsedOutputCalendar || null;
    this.weekSettings = weekSettings;
    this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);
    this.weekdaysCache = { format: {}, standalone: {} };
    this.monthsCache = { format: {}, standalone: {} };
    this.meridiemCache = null;
    this.eraCache = {};
    this.specifiedLocale = specifiedLocale;
    this.fastNumbersCached = null;
  }
  get fastNumbers() {
    if (this.fastNumbersCached == null) {
      this.fastNumbersCached = supportsFastNumbers(this);
    }
    return this.fastNumbersCached;
  }
  listingMode() {
    const isActuallyEn = this.isEnglish();
    const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory");
    return isActuallyEn && hasNoWeirdness ? "en" : "intl";
  }
  clone(alts) {
    if (!alts || Object.getOwnPropertyNames(alts).length === 0) {
      return this;
    } else {
      return _Locale.create(
        alts.locale || this.specifiedLocale,
        alts.numberingSystem || this.numberingSystem,
        alts.outputCalendar || this.outputCalendar,
        validateWeekSettings(alts.weekSettings) || this.weekSettings,
        alts.defaultToEN || false
      );
    }
  }
  redefaultToEN(alts = {}) {
    return this.clone({ ...alts, defaultToEN: true });
  }
  redefaultToSystem(alts = {}) {
    return this.clone({ ...alts, defaultToEN: false });
  }
  months(length, format2 = false) {
    return listStuff(this, length, months, () => {
      const monthSpecialCase = this.intl === "ja" || this.intl.startsWith("ja-");
      format2 &= !monthSpecialCase;
      const intl = format2 ? { month: length, day: "numeric" } : { month: length }, formatStr = format2 ? "format" : "standalone";
      if (!this.monthsCache[formatStr][length]) {
        const mapper = !monthSpecialCase ? (dt) => this.extract(dt, intl, "month") : (dt) => this.dtFormatter(dt, intl).format();
        this.monthsCache[formatStr][length] = mapMonths(mapper);
      }
      return this.monthsCache[formatStr][length];
    });
  }
  weekdays(length, format2 = false) {
    return listStuff(this, length, weekdays, () => {
      const intl = format2 ? { weekday: length, year: "numeric", month: "long", day: "numeric" } : { weekday: length }, formatStr = format2 ? "format" : "standalone";
      if (!this.weekdaysCache[formatStr][length]) {
        this.weekdaysCache[formatStr][length] = mapWeekdays(
          (dt) => this.extract(dt, intl, "weekday")
        );
      }
      return this.weekdaysCache[formatStr][length];
    });
  }
  meridiems() {
    return listStuff(
      this,
      void 0,
      () => meridiems,
      () => {
        if (!this.meridiemCache) {
          const intl = { hour: "numeric", hourCycle: "h12" };
          this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(
            (dt) => this.extract(dt, intl, "dayperiod")
          );
        }
        return this.meridiemCache;
      }
    );
  }
  eras(length) {
    return listStuff(this, length, eras, () => {
      const intl = { era: length };
      if (!this.eraCache[length]) {
        this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(
          (dt) => this.extract(dt, intl, "era")
        );
      }
      return this.eraCache[length];
    });
  }
  extract(dt, intlOpts, field) {
    const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find((m) => m.type.toLowerCase() === field);
    return matching ? matching.value : null;
  }
  numberFormatter(opts = {}) {
    return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);
  }
  dtFormatter(dt, intlOpts = {}) {
    return new PolyDateFormatter(dt, this.intl, intlOpts);
  }
  relFormatter(opts = {}) {
    return new PolyRelFormatter(this.intl, this.isEnglish(), opts);
  }
  listFormatter(opts = {}) {
    return getCachedLF(this.intl, opts);
  }
  isEnglish() {
    return this.locale === "en" || this.locale.toLowerCase() === "en-us" || getCachedIntResolvedOptions(this.intl).locale.startsWith("en-us");
  }
  getWeekSettings() {
    if (this.weekSettings) {
      return this.weekSettings;
    } else if (!hasLocaleWeekInfo()) {
      return fallbackWeekSettings;
    } else {
      return getCachedWeekInfo(this.locale);
    }
  }
  getStartOfWeek() {
    return this.getWeekSettings().firstDay;
  }
  getMinDaysInFirstWeek() {
    return this.getWeekSettings().minimalDays;
  }
  getWeekendDays() {
    return this.getWeekSettings().weekend;
  }
  equals(other) {
    return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar;
  }
  toString() {
    return `Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`;
  }
};
var singleton = null;
var FixedOffsetZone = class _FixedOffsetZone extends Zone {
  /**
   * Get a singleton instance of UTC
   * @return {FixedOffsetZone}
   */
  static get utcInstance() {
    if (singleton === null) {
      singleton = new _FixedOffsetZone(0);
    }
    return singleton;
  }
  /**
   * Get an instance with a specified offset
   * @param {number} offset - The offset in minutes
   * @return {FixedOffsetZone}
   */
  static instance(offset2) {
    return offset2 === 0 ? _FixedOffsetZone.utcInstance : new _FixedOffsetZone(offset2);
  }
  /**
   * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6"
   * @param {string} s - The offset string to parse
   * @example FixedOffsetZone.parseSpecifier("UTC+6")
   * @example FixedOffsetZone.parseSpecifier("UTC+06")
   * @example FixedOffsetZone.parseSpecifier("UTC-6:00")
   * @return {FixedOffsetZone}
   */
  static parseSpecifier(s2) {
    if (s2) {
      const r = s2.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);
      if (r) {
        return new _FixedOffsetZone(signedOffset(r[1], r[2]));
      }
    }
    return null;
  }
  constructor(offset2) {
    super();
    this.fixed = offset2;
  }
  /**
   * The type of zone. `fixed` for all instances of `FixedOffsetZone`.
   * @override
   * @type {string}
   */
  get type() {
    return "fixed";
  }
  /**
   * The name of this zone.
   * All fixed zones' names always start with "UTC" (plus optional offset)
   * @override
   * @type {string}
   */
  get name() {
    return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`;
  }
  /**
   * The IANA name of this zone, i.e. `Etc/UTC` or `Etc/GMT+/-nn`
   *
   * @override
   * @type {string}
   */
  get ianaName() {
    if (this.fixed === 0) {
      return "Etc/UTC";
    } else {
      return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`;
    }
  }
  /**
   * Returns the offset's common name at the specified timestamp.
   *
   * For fixed offset zones this equals to the zone name.
   * @override
   */
  offsetName() {
    return this.name;
  }
  /**
   * Returns the offset's value as a string
   * @override
   * @param {number} ts - Epoch milliseconds for which to get the offset
   * @param {string} format - What style of offset to return.
   *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
   * @return {string}
   */
  formatOffset(ts, format2) {
    return formatOffset(this.fixed, format2);
  }
  /**
   * Returns whether the offset is known to be fixed for the whole year:
   * Always returns true for all fixed offset zones.
   * @override
   * @type {boolean}
   */
  get isUniversal() {
    return true;
  }
  /**
   * Return the offset in minutes for this zone at the specified timestamp.
   *
   * For fixed offset zones, this is constant and does not depend on a timestamp.
   * @override
   * @return {number}
   */
  offset() {
    return this.fixed;
  }
  /**
   * Return whether this Zone is equal to another zone (i.e. also fixed and same offset)
   * @override
   * @param {Zone} otherZone - the zone to compare
   * @return {boolean}
   */
  equals(otherZone) {
    return otherZone.type === "fixed" && otherZone.fixed === this.fixed;
  }
  /**
   * Return whether this Zone is valid:
   * All fixed offset zones are valid.
   * @override
   * @type {boolean}
   */
  get isValid() {
    return true;
  }
};
var InvalidZone = class extends Zone {
  constructor(zoneName) {
    super();
    this.zoneName = zoneName;
  }
  /** @override **/
  get type() {
    return "invalid";
  }
  /** @override **/
  get name() {
    return this.zoneName;
  }
  /** @override **/
  get isUniversal() {
    return false;
  }
  /** @override **/
  offsetName() {
    return null;
  }
  /** @override **/
  formatOffset() {
    return "";
  }
  /** @override **/
  offset() {
    return NaN;
  }
  /** @override **/
  equals() {
    return false;
  }
  /** @override **/
  get isValid() {
    return false;
  }
};
function normalizeZone(input, defaultZone2) {
  if (isUndefined(input) || input === null) {
    return defaultZone2;
  } else if (input instanceof Zone) {
    return input;
  } else if (isString(input)) {
    const lowered = input.toLowerCase();
    if (lowered === "default") return defaultZone2;
    else if (lowered === "local" || lowered === "system") return SystemZone.instance;
    else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance;
    else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);
  } else if (isNumber(input)) {
    return FixedOffsetZone.instance(input);
  } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") {
    return input;
  } else {
    return new InvalidZone(input);
  }
}
var numberingSystems = {
  arab: "[\u0660-\u0669]",
  arabext: "[\u06F0-\u06F9]",
  bali: "[\u1B50-\u1B59]",
  beng: "[\u09E6-\u09EF]",
  deva: "[\u0966-\u096F]",
  fullwide: "[\uFF10-\uFF19]",
  gujr: "[\u0AE6-\u0AEF]",
  hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",
  khmr: "[\u17E0-\u17E9]",
  knda: "[\u0CE6-\u0CEF]",
  laoo: "[\u0ED0-\u0ED9]",
  limb: "[\u1946-\u194F]",
  mlym: "[\u0D66-\u0D6F]",
  mong: "[\u1810-\u1819]",
  mymr: "[\u1040-\u1049]",
  orya: "[\u0B66-\u0B6F]",
  tamldec: "[\u0BE6-\u0BEF]",
  telu: "[\u0C66-\u0C6F]",
  thai: "[\u0E50-\u0E59]",
  tibt: "[\u0F20-\u0F29]",
  latn: "\\d"
};
var numberingSystemsUTF16 = {
  arab: [1632, 1641],
  arabext: [1776, 1785],
  bali: [6992, 7001],
  beng: [2534, 2543],
  deva: [2406, 2415],
  fullwide: [65296, 65303],
  gujr: [2790, 2799],
  khmr: [6112, 6121],
  knda: [3302, 3311],
  laoo: [3792, 3801],
  limb: [6470, 6479],
  mlym: [3430, 3439],
  mong: [6160, 6169],
  mymr: [4160, 4169],
  orya: [2918, 2927],
  tamldec: [3046, 3055],
  telu: [3174, 3183],
  thai: [3664, 3673],
  tibt: [3872, 3881]
};
var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split("");
function parseDigits(str) {
  let value = parseInt(str, 10);
  if (isNaN(value)) {
    value = "";
    for (let i = 0; i < str.length; i++) {
      const code = str.charCodeAt(i);
      if (str[i].search(numberingSystems.hanidec) !== -1) {
        value += hanidecChars.indexOf(str[i]);
      } else {
        for (const key in numberingSystemsUTF16) {
          const [min, max] = numberingSystemsUTF16[key];
          if (code >= min && code <= max) {
            value += code - min;
          }
        }
      }
    }
    return parseInt(value, 10);
  } else {
    return value;
  }
}
var digitRegexCache = /* @__PURE__ */ new Map();
function resetDigitRegexCache() {
  digitRegexCache.clear();
}
function digitRegex({ numberingSystem }, append2 = "") {
  const ns = numberingSystem || "latn";
  let appendCache = digitRegexCache.get(ns);
  if (appendCache === void 0) {
    appendCache = /* @__PURE__ */ new Map();
    digitRegexCache.set(ns, appendCache);
  }
  let regex = appendCache.get(append2);
  if (regex === void 0) {
    regex = new RegExp(`${numberingSystems[ns]}${append2}`);
    appendCache.set(append2, regex);
  }
  return regex;
}
var now = () => Date.now();
var defaultZone = "system";
var defaultLocale = null;
var defaultNumberingSystem = null;
var defaultOutputCalendar = null;
var twoDigitCutoffYear = 60;
var throwOnInvalid;
var defaultWeekSettings = null;
var Settings = class {
  /**
   * Get the callback for returning the current timestamp.
   * @type {function}
   */
  static get now() {
    return now;
  }
  /**
   * Set the callback for returning the current timestamp.
   * The function should return a number, which will be interpreted as an Epoch millisecond count
   * @type {function}
   * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future
   * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time
   */
  static set now(n2) {
    now = n2;
  }
  /**
   * Set the default time zone to create DateTimes in. Does not affect existing instances.
   * Use the value "system" to reset this value to the system's time zone.
   * @type {string}
   */
  static set defaultZone(zone) {
    defaultZone = zone;
  }
  /**
   * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.
   * The default value is the system's time zone (the one set on the machine that runs this code).
   * @type {Zone}
   */
  static get defaultZone() {
    return normalizeZone(defaultZone, SystemZone.instance);
  }
  /**
   * Get the default locale to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static get defaultLocale() {
    return defaultLocale;
  }
  /**
   * Set the default locale to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static set defaultLocale(locale3) {
    defaultLocale = locale3;
  }
  /**
   * Get the default numbering system to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static get defaultNumberingSystem() {
    return defaultNumberingSystem;
  }
  /**
   * Set the default numbering system to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static set defaultNumberingSystem(numberingSystem) {
    defaultNumberingSystem = numberingSystem;
  }
  /**
   * Get the default output calendar to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static get defaultOutputCalendar() {
    return defaultOutputCalendar;
  }
  /**
   * Set the default output calendar to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static set defaultOutputCalendar(outputCalendar) {
    defaultOutputCalendar = outputCalendar;
  }
  /**
   * @typedef {Object} WeekSettings
   * @property {number} firstDay
   * @property {number} minimalDays
   * @property {number[]} weekend
   */
  /**
   * @return {WeekSettings|null}
   */
  static get defaultWeekSettings() {
    return defaultWeekSettings;
  }
  /**
   * Allows overriding the default locale week settings, i.e. the start of the week, the weekend and
   * how many days are required in the first week of a year.
   * Does not affect existing instances.
   *
   * @param {WeekSettings|null} weekSettings
   */
  static set defaultWeekSettings(weekSettings) {
    defaultWeekSettings = validateWeekSettings(weekSettings);
  }
  /**
   * Get the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx.
   * @type {number}
   */
  static get twoDigitCutoffYear() {
    return twoDigitCutoffYear;
  }
  /**
   * Set the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx.
   * @type {number}
   * @example Settings.twoDigitCutoffYear = 0 // all 'yy' are interpreted as 20th century
   * @example Settings.twoDigitCutoffYear = 99 // all 'yy' are interpreted as 21st century
   * @example Settings.twoDigitCutoffYear = 50 // '49' -> 2049; '50' -> 1950
   * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50
   * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted as 50
   */
  static set twoDigitCutoffYear(cutoffYear) {
    twoDigitCutoffYear = cutoffYear % 100;
  }
  /**
   * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
   * @type {boolean}
   */
  static get throwOnInvalid() {
    return throwOnInvalid;
  }
  /**
   * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
   * @type {boolean}
   */
  static set throwOnInvalid(t) {
    throwOnInvalid = t;
  }
  /**
   * Reset Luxon's global caches. Should only be necessary in testing scenarios.
   * @return {void}
   */
  static resetCaches() {
    Locale.resetCache();
    IANAZone.resetCache();
    DateTime.resetCache();
    resetDigitRegexCache();
  }
};
var Invalid = class {
  constructor(reason, explanation) {
    this.reason = reason;
    this.explanation = explanation;
  }
  toMessage() {
    if (this.explanation) {
      return `${this.reason}: ${this.explanation}`;
    } else {
      return this.reason;
    }
  }
};
var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
function unitOutOfRange(unit3, value) {
  return new Invalid(
    "unit out of range",
    `you specified ${value} (of type ${typeof value}) as a ${unit3}, which is invalid`
  );
}
function dayOfWeek(year, month, day) {
  const d = new Date(Date.UTC(year, month - 1, day));
  if (year < 100 && year >= 0) {
    d.setUTCFullYear(d.getUTCFullYear() - 1900);
  }
  const js = d.getUTCDay();
  return js === 0 ? 7 : js;
}
function computeOrdinal(year, month, day) {
  return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];
}
function uncomputeOrdinal(year, ordinal) {
  const table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex((i) => i < ordinal), day = ordinal - table[month0];
  return { month: month0 + 1, day };
}
function isoWeekdayToLocal(isoWeekday, startOfWeek) {
  return (isoWeekday - startOfWeek + 7) % 7 + 1;
}
function gregorianToWeek(gregObj, minDaysInFirstWeek = 4, startOfWeek = 1) {
  const { year, month, day } = gregObj, ordinal = computeOrdinal(year, month, day), weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek);
  let weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7), weekYear;
  if (weekNumber < 1) {
    weekYear = year - 1;
    weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek);
  } else if (weekNumber > weeksInWeekYear(year, minDaysInFirstWeek, startOfWeek)) {
    weekYear = year + 1;
    weekNumber = 1;
  } else {
    weekYear = year;
  }
  return { weekYear, weekNumber, weekday, ...timeObject(gregObj) };
}
function weekToGregorian(weekData, minDaysInFirstWeek = 4, startOfWeek = 1) {
  const { weekYear, weekNumber, weekday } = weekData, weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek), yearInDays = daysInYear(weekYear);
  let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek, year;
  if (ordinal < 1) {
    year = weekYear - 1;
    ordinal += daysInYear(year);
  } else if (ordinal > yearInDays) {
    year = weekYear + 1;
    ordinal -= daysInYear(weekYear);
  } else {
    year = weekYear;
  }
  const { month, day } = uncomputeOrdinal(year, ordinal);
  return { year, month, day, ...timeObject(weekData) };
}
function gregorianToOrdinal(gregData) {
  const { year, month, day } = gregData;
  const ordinal = computeOrdinal(year, month, day);
  return { year, ordinal, ...timeObject(gregData) };
}
function ordinalToGregorian(ordinalData) {
  const { year, ordinal } = ordinalData;
  const { month, day } = uncomputeOrdinal(year, ordinal);
  return { year, month, day, ...timeObject(ordinalData) };
}
function usesLocalWeekValues(obj, loc) {
  const hasLocaleWeekData = !isUndefined(obj.localWeekday) || !isUndefined(obj.localWeekNumber) || !isUndefined(obj.localWeekYear);
  if (hasLocaleWeekData) {
    const hasIsoWeekData = !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear);
    if (hasIsoWeekData) {
      throw new ConflictingSpecificationError(
        "Cannot mix locale-based week fields with ISO-based week fields"
      );
    }
    if (!isUndefined(obj.localWeekday)) obj.weekday = obj.localWeekday;
    if (!isUndefined(obj.localWeekNumber)) obj.weekNumber = obj.localWeekNumber;
    if (!isUndefined(obj.localWeekYear)) obj.weekYear = obj.localWeekYear;
    delete obj.localWeekday;
    delete obj.localWeekNumber;
    delete obj.localWeekYear;
    return {
      minDaysInFirstWeek: loc.getMinDaysInFirstWeek(),
      startOfWeek: loc.getStartOfWeek()
    };
  } else {
    return { minDaysInFirstWeek: 4, startOfWeek: 1 };
  }
}
function hasInvalidWeekData(obj, minDaysInFirstWeek = 4, startOfWeek = 1) {
  const validYear = isInteger(obj.weekYear), validWeek = integerBetween(
    obj.weekNumber,
    1,
    weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek)
  ), validWeekday = integerBetween(obj.weekday, 1, 7);
  if (!validYear) {
    return unitOutOfRange("weekYear", obj.weekYear);
  } else if (!validWeek) {
    return unitOutOfRange("week", obj.weekNumber);
  } else if (!validWeekday) {
    return unitOutOfRange("weekday", obj.weekday);
  } else return false;
}
function hasInvalidOrdinalData(obj) {
  const validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));
  if (!validYear) {
    return unitOutOfRange("year", obj.year);
  } else if (!validOrdinal) {
    return unitOutOfRange("ordinal", obj.ordinal);
  } else return false;
}
function hasInvalidGregorianData(obj) {
  const validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));
  if (!validYear) {
    return unitOutOfRange("year", obj.year);
  } else if (!validMonth) {
    return unitOutOfRange("month", obj.month);
  } else if (!validDay) {
    return unitOutOfRange("day", obj.day);
  } else return false;
}
function hasInvalidTimeData(obj) {
  const { hour, minute, second: second2, millisecond: millisecond2 } = obj;
  const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second2 === 0 && millisecond2 === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second2, 0, 59), validMillisecond = integerBetween(millisecond2, 0, 999);
  if (!validHour) {
    return unitOutOfRange("hour", hour);
  } else if (!validMinute) {
    return unitOutOfRange("minute", minute);
  } else if (!validSecond) {
    return unitOutOfRange("second", second2);
  } else if (!validMillisecond) {
    return unitOutOfRange("millisecond", millisecond2);
  } else return false;
}
function isUndefined(o) {
  return typeof o === "undefined";
}
function isNumber(o) {
  return typeof o === "number";
}
function isInteger(o) {
  return typeof o === "number" && o % 1 === 0;
}
function isString(o) {
  return typeof o === "string";
}
function isDate(o) {
  return Object.prototype.toString.call(o) === "[object Date]";
}
function hasRelative() {
  try {
    return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat;
  } catch (e) {
    return false;
  }
}
function hasLocaleWeekInfo() {
  try {
    return typeof Intl !== "undefined" && !!Intl.Locale && ("weekInfo" in Intl.Locale.prototype || "getWeekInfo" in Intl.Locale.prototype);
  } catch (e) {
    return false;
  }
}
function maybeArray(thing) {
  return Array.isArray(thing) ? thing : [thing];
}
function bestBy(arr, by, compare) {
  if (arr.length === 0) {
    return void 0;
  }
  return arr.reduce((best, next) => {
    const pair = [by(next), next];
    if (!best) {
      return pair;
    } else if (compare(best[0], pair[0]) === best[0]) {
      return best;
    } else {
      return pair;
    }
  }, null)[1];
}
function pick(obj, keys) {
  return keys.reduce((a, k) => {
    a[k] = obj[k];
    return a;
  }, {});
}
function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}
function validateWeekSettings(settings) {
  if (settings == null) {
    return null;
  } else if (typeof settings !== "object") {
    throw new InvalidArgumentError("Week settings must be an object");
  } else {
    if (!integerBetween(settings.firstDay, 1, 7) || !integerBetween(settings.minimalDays, 1, 7) || !Array.isArray(settings.weekend) || settings.weekend.some((v) => !integerBetween(v, 1, 7))) {
      throw new InvalidArgumentError("Invalid week settings");
    }
    return {
      firstDay: settings.firstDay,
      minimalDays: settings.minimalDays,
      weekend: Array.from(settings.weekend)
    };
  }
}
function integerBetween(thing, bottom2, top2) {
  return isInteger(thing) && thing >= bottom2 && thing <= top2;
}
function floorMod(x2, n2) {
  return x2 - n2 * Math.floor(x2 / n2);
}
function padStart(input, n2 = 2) {
  const isNeg = input < 0;
  let padded;
  if (isNeg) {
    padded = "-" + ("" + -input).padStart(n2, "0");
  } else {
    padded = ("" + input).padStart(n2, "0");
  }
  return padded;
}
function parseInteger(string4) {
  if (isUndefined(string4) || string4 === null || string4 === "") {
    return void 0;
  } else {
    return parseInt(string4, 10);
  }
}
function parseFloating(string4) {
  if (isUndefined(string4) || string4 === null || string4 === "") {
    return void 0;
  } else {
    return parseFloat(string4);
  }
}
function parseMillis(fraction) {
  if (isUndefined(fraction) || fraction === null || fraction === "") {
    return void 0;
  } else {
    const f = parseFloat("0." + fraction) * 1e3;
    return Math.floor(f);
  }
}
function roundTo(number8, digits, rounding = "round") {
  const factor = 10 ** digits;
  switch (rounding) {
    case "expand":
      return number8 > 0 ? Math.ceil(number8 * factor) / factor : Math.floor(number8 * factor) / factor;
    case "trunc":
      return Math.trunc(number8 * factor) / factor;
    case "round":
      return Math.round(number8 * factor) / factor;
    case "floor":
      return Math.floor(number8 * factor) / factor;
    case "ceil":
      return Math.ceil(number8 * factor) / factor;
    default:
      throw new RangeError(`Value rounding ${rounding} is out of range`);
  }
}
function isLeapYear(year) {
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function daysInYear(year) {
  return isLeapYear(year) ? 366 : 365;
}
function daysInMonth(year, month) {
  const modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12;
  if (modMonth === 2) {
    return isLeapYear(modYear) ? 29 : 28;
  } else {
    return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];
  }
}
function objToLocalTS(obj) {
  let d = Date.UTC(
    obj.year,
    obj.month - 1,
    obj.day,
    obj.hour,
    obj.minute,
    obj.second,
    obj.millisecond
  );
  if (obj.year < 100 && obj.year >= 0) {
    d = new Date(d);
    d.setUTCFullYear(obj.year, obj.month - 1, obj.day);
  }
  return +d;
}
function firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) {
  const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek);
  return -fwdlw + minDaysInFirstWeek - 1;
}
function weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) {
  const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek);
  const weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek);
  return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7;
}
function untruncateYear(year) {
  if (year > 99) {
    return year;
  } else return year > Settings.twoDigitCutoffYear ? 1900 + year : 2e3 + year;
}
function parseZoneInfo(ts, offsetFormat, locale3, timeZone = null) {
  const date6 = new Date(ts), intlOpts = {
    hourCycle: "h23",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit"
  };
  if (timeZone) {
    intlOpts.timeZone = timeZone;
  }
  const modified = { timeZoneName: offsetFormat, ...intlOpts };
  const parsed = new Intl.DateTimeFormat(locale3, modified).formatToParts(date6).find((m) => m.type.toLowerCase() === "timezonename");
  return parsed ? parsed.value : null;
}
function signedOffset(offHourStr, offMinuteStr) {
  let offHour = parseInt(offHourStr, 10);
  if (Number.isNaN(offHour)) {
    offHour = 0;
  }
  const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;
  return offHour * 60 + offMinSigned;
}
function asNumber(value) {
  const numericValue = Number(value);
  if (typeof value === "boolean" || value === "" || !Number.isFinite(numericValue))
    throw new InvalidArgumentError(`Invalid unit value ${value}`);
  return numericValue;
}
function normalizeObject(obj, normalizer) {
  const normalized = {};
  for (const u in obj) {
    if (hasOwnProperty(obj, u)) {
      const v = obj[u];
      if (v === void 0 || v === null) continue;
      normalized[normalizer(u)] = asNumber(v);
    }
  }
  return normalized;
}
function formatOffset(offset2, format2) {
  const hours = Math.trunc(Math.abs(offset2 / 60)), minutes = Math.trunc(Math.abs(offset2 % 60)), sign = offset2 >= 0 ? "+" : "-";
  switch (format2) {
    case "short":
      return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;
    case "narrow":
      return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`;
    case "techie":
      return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;
    default:
      throw new RangeError(`Value format ${format2} is out of range for property format`);
  }
}
function timeObject(obj) {
  return pick(obj, ["hour", "minute", "second", "millisecond"]);
}
var monthsLong = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
];
var monthsShort = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec"
];
var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"];
function months(length) {
  switch (length) {
    case "narrow":
      return [...monthsNarrow];
    case "short":
      return [...monthsShort];
    case "long":
      return [...monthsLong];
    case "numeric":
      return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
    case "2-digit":
      return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
    default:
      return null;
  }
}
var weekdaysLong = [
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
  "Sunday"
];
var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"];
function weekdays(length) {
  switch (length) {
    case "narrow":
      return [...weekdaysNarrow];
    case "short":
      return [...weekdaysShort];
    case "long":
      return [...weekdaysLong];
    case "numeric":
      return ["1", "2", "3", "4", "5", "6", "7"];
    default:
      return null;
  }
}
var meridiems = ["AM", "PM"];
var erasLong = ["Before Christ", "Anno Domini"];
var erasShort = ["BC", "AD"];
var erasNarrow = ["B", "A"];
function eras(length) {
  switch (length) {
    case "narrow":
      return [...erasNarrow];
    case "short":
      return [...erasShort];
    case "long":
      return [...erasLong];
    default:
      return null;
  }
}
function meridiemForDateTime(dt) {
  return meridiems[dt.hour < 12 ? 0 : 1];
}
function weekdayForDateTime(dt, length) {
  return weekdays(length)[dt.weekday - 1];
}
function monthForDateTime(dt, length) {
  return months(length)[dt.month - 1];
}
function eraForDateTime(dt, length) {
  return eras(length)[dt.year < 0 ? 0 : 1];
}
function formatRelativeTime(unit3, count, numeric = "always", narrow = false) {
  const units = {
    years: ["year", "yr."],
    quarters: ["quarter", "qtr."],
    months: ["month", "mo."],
    weeks: ["week", "wk."],
    days: ["day", "day", "days"],
    hours: ["hour", "hr."],
    minutes: ["minute", "min."],
    seconds: ["second", "sec."]
  };
  const lastable = ["hours", "minutes", "seconds"].indexOf(unit3) === -1;
  if (numeric === "auto" && lastable) {
    const isDay = unit3 === "days";
    switch (count) {
      case 1:
        return isDay ? "tomorrow" : `next ${units[unit3][0]}`;
      case -1:
        return isDay ? "yesterday" : `last ${units[unit3][0]}`;
      case 0:
        return isDay ? "today" : `this ${units[unit3][0]}`;
    }
  }
  const isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit3], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit3][0] : unit3;
  return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;
}
function stringifyTokens(splits, tokenToString) {
  let s2 = "";
  for (const token of splits) {
    if (token.literal) {
      s2 += token.val;
    } else {
      s2 += tokenToString(token.val);
    }
  }
  return s2;
}
var macroTokenToFormatOpts = {
  D: DATE_SHORT,
  DD: DATE_MED,
  DDD: DATE_FULL,
  DDDD: DATE_HUGE,
  t: TIME_SIMPLE,
  tt: TIME_WITH_SECONDS,
  ttt: TIME_WITH_SHORT_OFFSET,
  tttt: TIME_WITH_LONG_OFFSET,
  T: TIME_24_SIMPLE,
  TT: TIME_24_WITH_SECONDS,
  TTT: TIME_24_WITH_SHORT_OFFSET,
  TTTT: TIME_24_WITH_LONG_OFFSET,
  f: DATETIME_SHORT,
  ff: DATETIME_MED,
  fff: DATETIME_FULL,
  ffff: DATETIME_HUGE,
  F: DATETIME_SHORT_WITH_SECONDS,
  FF: DATETIME_MED_WITH_SECONDS,
  FFF: DATETIME_FULL_WITH_SECONDS,
  FFFF: DATETIME_HUGE_WITH_SECONDS
};
var Formatter = class _Formatter {
  static create(locale3, opts = {}) {
    return new _Formatter(locale3, opts);
  }
  static parseFormat(fmt) {
    let current = null, currentFull = "", bracketed = false;
    const splits = [];
    for (let i = 0; i < fmt.length; i++) {
      const c = fmt.charAt(i);
      if (c === "'") {
        if (currentFull.length > 0 || bracketed) {
          splits.push({
            literal: bracketed || /^\s+$/.test(currentFull),
            val: currentFull === "" ? "'" : currentFull
          });
        }
        current = null;
        currentFull = "";
        bracketed = !bracketed;
      } else if (bracketed) {
        currentFull += c;
      } else if (c === current) {
        currentFull += c;
      } else {
        if (currentFull.length > 0) {
          splits.push({ literal: /^\s+$/.test(currentFull), val: currentFull });
        }
        currentFull = c;
        current = c;
      }
    }
    if (currentFull.length > 0) {
      splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull });
    }
    return splits;
  }
  static macroTokenToFormatOpts(token) {
    return macroTokenToFormatOpts[token];
  }
  constructor(locale3, formatOpts) {
    this.opts = formatOpts;
    this.loc = locale3;
    this.systemLoc = null;
  }
  formatWithSystemDefault(dt, opts) {
    if (this.systemLoc === null) {
      this.systemLoc = this.loc.redefaultToSystem();
    }
    const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts });
    return df.format();
  }
  dtFormatter(dt, opts = {}) {
    return this.loc.dtFormatter(dt, { ...this.opts, ...opts });
  }
  formatDateTime(dt, opts) {
    return this.dtFormatter(dt, opts).format();
  }
  formatDateTimeParts(dt, opts) {
    return this.dtFormatter(dt, opts).formatToParts();
  }
  formatInterval(interval2, opts) {
    const df = this.dtFormatter(interval2.start, opts);
    return df.dtf.formatRange(interval2.start.toJSDate(), interval2.end.toJSDate());
  }
  resolvedOptions(dt, opts) {
    return this.dtFormatter(dt, opts).resolvedOptions();
  }
  num(n2, p = 0, signDisplay = void 0) {
    if (this.opts.forceSimple) {
      return padStart(n2, p);
    }
    const opts = { ...this.opts };
    if (p > 0) {
      opts.padTo = p;
    }
    if (signDisplay) {
      opts.signDisplay = signDisplay;
    }
    return this.loc.numberFormatter(opts).format(n2);
  }
  formatDateTimeFromString(dt, fmt) {
    const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string4 = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset2 = (opts) => {
      if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {
        return "Z";
      }
      return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : "";
    }, meridiem = () => knownEnglish ? meridiemForDateTime(dt) : string4({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string4(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string4(
      standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" },
      "weekday"
    ), maybeMacro = (token) => {
      const formatOpts = _Formatter.macroTokenToFormatOpts(token);
      if (formatOpts) {
        return this.formatWithSystemDefault(dt, formatOpts);
      } else {
        return token;
      }
    }, era = (length) => knownEnglish ? eraForDateTime(dt, length) : string4({ era: length }, "era"), tokenToString = (token) => {
      switch (token) {
        // ms
        case "S":
          return this.num(dt.millisecond);
        case "u":
        // falls through
        case "SSS":
          return this.num(dt.millisecond, 3);
        // seconds
        case "s":
          return this.num(dt.second);
        case "ss":
          return this.num(dt.second, 2);
        // fractional seconds
        case "uu":
          return this.num(Math.floor(dt.millisecond / 10), 2);
        case "uuu":
          return this.num(Math.floor(dt.millisecond / 100));
        // minutes
        case "m":
          return this.num(dt.minute);
        case "mm":
          return this.num(dt.minute, 2);
        // hours
        case "h":
          return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);
        case "hh":
          return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);
        case "H":
          return this.num(dt.hour);
        case "HH":
          return this.num(dt.hour, 2);
        // offset
        case "Z":
          return formatOffset2({ format: "narrow", allowZ: this.opts.allowZ });
        case "ZZ":
          return formatOffset2({ format: "short", allowZ: this.opts.allowZ });
        case "ZZZ":
          return formatOffset2({ format: "techie", allowZ: this.opts.allowZ });
        case "ZZZZ":
          return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale });
        case "ZZZZZ":
          return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale });
        // zone
        case "z":
          return dt.zoneName;
        // meridiems
        case "a":
          return meridiem();
        // dates
        case "d":
          return useDateTimeFormatter ? string4({ day: "numeric" }, "day") : this.num(dt.day);
        case "dd":
          return useDateTimeFormatter ? string4({ day: "2-digit" }, "day") : this.num(dt.day, 2);
        // weekdays - standalone
        case "c":
          return this.num(dt.weekday);
        case "ccc":
          return weekday("short", true);
        case "cccc":
          return weekday("long", true);
        case "ccccc":
          return weekday("narrow", true);
        // weekdays - format
        case "E":
          return this.num(dt.weekday);
        case "EEE":
          return weekday("short", false);
        case "EEEE":
          return weekday("long", false);
        case "EEEEE":
          return weekday("narrow", false);
        // months - standalone
        case "L":
          return useDateTimeFormatter ? string4({ month: "numeric", day: "numeric" }, "month") : this.num(dt.month);
        case "LL":
          return useDateTimeFormatter ? string4({ month: "2-digit", day: "numeric" }, "month") : this.num(dt.month, 2);
        case "LLL":
          return month("short", true);
        case "LLLL":
          return month("long", true);
        case "LLLLL":
          return month("narrow", true);
        // months - format
        case "M":
          return useDateTimeFormatter ? string4({ month: "numeric" }, "month") : this.num(dt.month);
        case "MM":
          return useDateTimeFormatter ? string4({ month: "2-digit" }, "month") : this.num(dt.month, 2);
        case "MMM":
          return month("short", false);
        case "MMMM":
          return month("long", false);
        case "MMMMM":
          return month("narrow", false);
        // years
        case "y":
          return useDateTimeFormatter ? string4({ year: "numeric" }, "year") : this.num(dt.year);
        case "yy":
          return useDateTimeFormatter ? string4({ year: "2-digit" }, "year") : this.num(dt.year.toString().slice(-2), 2);
        case "yyyy":
          return useDateTimeFormatter ? string4({ year: "numeric" }, "year") : this.num(dt.year, 4);
        case "yyyyyy":
          return useDateTimeFormatter ? string4({ year: "numeric" }, "year") : this.num(dt.year, 6);
        // eras
        case "G":
          return era("short");
        case "GG":
          return era("long");
        case "GGGGG":
          return era("narrow");
        case "kk":
          return this.num(dt.weekYear.toString().slice(-2), 2);
        case "kkkk":
          return this.num(dt.weekYear, 4);
        case "W":
          return this.num(dt.weekNumber);
        case "WW":
          return this.num(dt.weekNumber, 2);
        case "n":
          return this.num(dt.localWeekNumber);
        case "nn":
          return this.num(dt.localWeekNumber, 2);
        case "ii":
          return this.num(dt.localWeekYear.toString().slice(-2), 2);
        case "iiii":
          return this.num(dt.localWeekYear, 4);
        case "o":
          return this.num(dt.ordinal);
        case "ooo":
          return this.num(dt.ordinal, 3);
        case "q":
          return this.num(dt.quarter);
        case "qq":
          return this.num(dt.quarter, 2);
        case "X":
          return this.num(Math.floor(dt.ts / 1e3));
        case "x":
          return this.num(dt.ts);
        default:
          return maybeMacro(token);
      }
    };
    return stringifyTokens(_Formatter.parseFormat(fmt), tokenToString);
  }
  formatDurationFromString(dur, fmt) {
    const invertLargest = this.opts.signMode === "negativeLargestOnly" ? -1 : 1;
    const tokenToField = (token) => {
      switch (token[0]) {
        case "S":
          return "milliseconds";
        case "s":
          return "seconds";
        case "m":
          return "minutes";
        case "h":
          return "hours";
        case "d":
          return "days";
        case "w":
          return "weeks";
        case "M":
          return "months";
        case "y":
          return "years";
        default:
          return null;
      }
    }, tokenToString = (lildur, info) => (token) => {
      const mapped = tokenToField(token);
      if (mapped) {
        const inversionFactor = info.isNegativeDuration && mapped !== info.largestUnit ? invertLargest : 1;
        let signDisplay;
        if (this.opts.signMode === "negativeLargestOnly" && mapped !== info.largestUnit) {
          signDisplay = "never";
        } else if (this.opts.signMode === "all") {
          signDisplay = "always";
        } else {
          signDisplay = "auto";
        }
        return this.num(lildur.get(mapped) * inversionFactor, token.length, signDisplay);
      } else {
        return token;
      }
    }, tokens = _Formatter.parseFormat(fmt), realTokens = tokens.reduce(
      (found, { literal: literal2, val }) => literal2 ? found : found.concat(val),
      []
    ), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t)), durationInfo = {
      isNegativeDuration: collapsed < 0,
      // this relies on "collapsed" being based on "shiftTo", which builds up the object
      // in order
      largestUnit: Object.keys(collapsed.values)[0]
    };
    return stringifyTokens(tokens, tokenToString(collapsed, durationInfo));
  }
};
var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;
function combineRegexes(...regexes) {
  const full = regexes.reduce((f, r) => f + r.source, "");
  return RegExp(`^${full}$`);
}
function combineExtractors(...extractors) {
  return (m) => extractors.reduce(
    ([mergedVals, mergedZone, cursor], ex) => {
      const [val, zone, next] = ex(m, cursor);
      return [{ ...mergedVals, ...val }, zone || mergedZone, next];
    },
    [{}, null, 1]
  ).slice(0, 2);
}
function parse(s2, ...patterns) {
  if (s2 == null) {
    return [null, null];
  }
  for (const [regex, extractor] of patterns) {
    const m = regex.exec(s2);
    if (m) {
      return extractor(m);
    }
  }
  return [null, null];
}
function simpleParse(...keys) {
  return (match2, cursor) => {
    const ret = {};
    let i;
    for (i = 0; i < keys.length; i++) {
      ret[keys[i]] = parseInteger(match2[cursor + i]);
    }
    return [ret, null, cursor + i];
  };
}
var offsetRegex = /(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/;
var isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`;
var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/;
var isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`);
var isoTimeExtensionRegex = RegExp(`(?:[Tt]${isoTimeRegex.source})?`);
var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/;
var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/;
var isoOrdinalRegex = /(\d{4})-?(\d{3})/;
var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay");
var extractISOOrdinalData = simpleParse("year", "ordinal");
var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/;
var sqlTimeRegex = RegExp(
  `${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`
);
var sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);
function int(match2, pos, fallback) {
  const m = match2[pos];
  return isUndefined(m) ? fallback : parseInteger(m);
}
function extractISOYmd(match2, cursor) {
  const item = {
    year: int(match2, cursor),
    month: int(match2, cursor + 1, 1),
    day: int(match2, cursor + 2, 1)
  };
  return [item, null, cursor + 3];
}
function extractISOTime(match2, cursor) {
  const item = {
    hours: int(match2, cursor, 0),
    minutes: int(match2, cursor + 1, 0),
    seconds: int(match2, cursor + 2, 0),
    milliseconds: parseMillis(match2[cursor + 3])
  };
  return [item, null, cursor + 4];
}
function extractISOOffset(match2, cursor) {
  const local = !match2[cursor] && !match2[cursor + 1], fullOffset = signedOffset(match2[cursor + 1], match2[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset);
  return [{}, zone, cursor + 3];
}
function extractIANAZone(match2, cursor) {
  const zone = match2[cursor] ? IANAZone.create(match2[cursor]) : null;
  return [{}, zone, cursor + 1];
}
var isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`);
var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;
function extractISODuration(match2) {
  const [s2, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match2;
  const hasNegativePrefix = s2[0] === "-";
  const negativeSeconds = secondStr && secondStr[0] === "-";
  const maybeNegate = (num, force = false) => num !== void 0 && (force || num && hasNegativePrefix) ? -num : num;
  return [
    {
      years: maybeNegate(parseFloating(yearStr)),
      months: maybeNegate(parseFloating(monthStr)),
      weeks: maybeNegate(parseFloating(weekStr)),
      days: maybeNegate(parseFloating(dayStr)),
      hours: maybeNegate(parseFloating(hourStr)),
      minutes: maybeNegate(parseFloating(minuteStr)),
      seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"),
      milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)
    }
  ];
}
var obsOffsets = {
  GMT: 0,
  EDT: -4 * 60,
  EST: -5 * 60,
  CDT: -5 * 60,
  CST: -6 * 60,
  MDT: -6 * 60,
  MST: -7 * 60,
  PDT: -7 * 60,
  PST: -8 * 60
};
function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
  const result = {
    year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),
    month: monthsShort.indexOf(monthStr) + 1,
    day: parseInteger(dayStr),
    hour: parseInteger(hourStr),
    minute: parseInteger(minuteStr)
  };
  if (secondStr) result.second = parseInteger(secondStr);
  if (weekdayStr) {
    result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1;
  }
  return result;
}
var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;
function extractRFC2822(match2) {
  const [
    ,
    weekdayStr,
    dayStr,
    monthStr,
    yearStr,
    hourStr,
    minuteStr,
    secondStr,
    obsOffset,
    milOffset,
    offHourStr,
    offMinuteStr
  ] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  let offset2;
  if (obsOffset) {
    offset2 = obsOffsets[obsOffset];
  } else if (milOffset) {
    offset2 = 0;
  } else {
    offset2 = signedOffset(offHourStr, offMinuteStr);
  }
  return [result, new FixedOffsetZone(offset2)];
}
function preprocessRFC2822(s2) {
  return s2.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim();
}
var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/;
var rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/;
var ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;
function extractRFC1123Or850(match2) {
  const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  return [result, FixedOffsetZone.utcInstance];
}
function extractASCII(match2) {
  const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  return [result, FixedOffsetZone.utcInstance];
}
var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);
var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);
var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);
var isoTimeCombinedRegex = combineRegexes(isoTimeRegex);
var extractISOYmdTimeAndOffset = combineExtractors(
  extractISOYmd,
  extractISOTime,
  extractISOOffset,
  extractIANAZone
);
var extractISOWeekTimeAndOffset = combineExtractors(
  extractISOWeekData,
  extractISOTime,
  extractISOOffset,
  extractIANAZone
);
var extractISOOrdinalDateAndTime = combineExtractors(
  extractISOOrdinalData,
  extractISOTime,
  extractISOOffset,
  extractIANAZone
);
var extractISOTimeAndOffset = combineExtractors(
  extractISOTime,
  extractISOOffset,
  extractIANAZone
);
function parseISODate(s2) {
  return parse(
    s2,
    [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],
    [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset],
    [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime],
    [isoTimeCombinedRegex, extractISOTimeAndOffset]
  );
}
function parseRFC2822Date(s2) {
  return parse(preprocessRFC2822(s2), [rfc2822, extractRFC2822]);
}
function parseHTTPDate(s2) {
  return parse(
    s2,
    [rfc1123, extractRFC1123Or850],
    [rfc850, extractRFC1123Or850],
    [ascii, extractASCII]
  );
}
function parseISODuration(s2) {
  return parse(s2, [isoDuration, extractISODuration]);
}
var extractISOTimeOnly = combineExtractors(extractISOTime);
function parseISOTimeOnly(s2) {
  return parse(s2, [isoTimeOnly, extractISOTimeOnly]);
}
var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);
var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);
var extractISOTimeOffsetAndIANAZone = combineExtractors(
  extractISOTime,
  extractISOOffset,
  extractIANAZone
);
function parseSQL(s2) {
  return parse(
    s2,
    [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],
    [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]
  );
}
var INVALID$2 = "Invalid Duration";
var lowOrderMatrix = {
  weeks: {
    days: 7,
    hours: 7 * 24,
    minutes: 7 * 24 * 60,
    seconds: 7 * 24 * 60 * 60,
    milliseconds: 7 * 24 * 60 * 60 * 1e3
  },
  days: {
    hours: 24,
    minutes: 24 * 60,
    seconds: 24 * 60 * 60,
    milliseconds: 24 * 60 * 60 * 1e3
  },
  hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1e3 },
  minutes: { seconds: 60, milliseconds: 60 * 1e3 },
  seconds: { milliseconds: 1e3 }
};
var casualMatrix = {
  years: {
    quarters: 4,
    months: 12,
    weeks: 52,
    days: 365,
    hours: 365 * 24,
    minutes: 365 * 24 * 60,
    seconds: 365 * 24 * 60 * 60,
    milliseconds: 365 * 24 * 60 * 60 * 1e3
  },
  quarters: {
    months: 3,
    weeks: 13,
    days: 91,
    hours: 91 * 24,
    minutes: 91 * 24 * 60,
    seconds: 91 * 24 * 60 * 60,
    milliseconds: 91 * 24 * 60 * 60 * 1e3
  },
  months: {
    weeks: 4,
    days: 30,
    hours: 30 * 24,
    minutes: 30 * 24 * 60,
    seconds: 30 * 24 * 60 * 60,
    milliseconds: 30 * 24 * 60 * 60 * 1e3
  },
  ...lowOrderMatrix
};
var daysInYearAccurate = 146097 / 400;
var daysInMonthAccurate = 146097 / 4800;
var accurateMatrix = {
  years: {
    quarters: 4,
    months: 12,
    weeks: daysInYearAccurate / 7,
    days: daysInYearAccurate,
    hours: daysInYearAccurate * 24,
    minutes: daysInYearAccurate * 24 * 60,
    seconds: daysInYearAccurate * 24 * 60 * 60,
    milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3
  },
  quarters: {
    months: 3,
    weeks: daysInYearAccurate / 28,
    days: daysInYearAccurate / 4,
    hours: daysInYearAccurate * 24 / 4,
    minutes: daysInYearAccurate * 24 * 60 / 4,
    seconds: daysInYearAccurate * 24 * 60 * 60 / 4,
    milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3 / 4
  },
  months: {
    weeks: daysInMonthAccurate / 7,
    days: daysInMonthAccurate,
    hours: daysInMonthAccurate * 24,
    minutes: daysInMonthAccurate * 24 * 60,
    seconds: daysInMonthAccurate * 24 * 60 * 60,
    milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1e3
  },
  ...lowOrderMatrix
};
var orderedUnits$1 = [
  "years",
  "quarters",
  "months",
  "weeks",
  "days",
  "hours",
  "minutes",
  "seconds",
  "milliseconds"
];
var reverseUnits = orderedUnits$1.slice(0).reverse();
function clone$1(dur, alts, clear = false) {
  const conf = {
    values: clear ? alts.values : { ...dur.values, ...alts.values || {} },
    loc: dur.loc.clone(alts.loc),
    conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,
    matrix: alts.matrix || dur.matrix
  };
  return new Duration(conf);
}
function durationToMillis(matrix, vals) {
  let sum = vals.milliseconds ?? 0;
  for (const unit3 of reverseUnits.slice(1)) {
    if (vals[unit3]) {
      sum += vals[unit3] * matrix[unit3]["milliseconds"];
    }
  }
  return sum;
}
function normalizeValues(matrix, vals) {
  const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1;
  orderedUnits$1.reduceRight((previous, current) => {
    if (!isUndefined(vals[current])) {
      if (previous) {
        const previousVal = vals[previous] * factor;
        const conv = matrix[current][previous];
        const rollUp = Math.floor(previousVal / conv);
        vals[current] += rollUp * factor;
        vals[previous] -= rollUp * conv * factor;
      }
      return current;
    } else {
      return previous;
    }
  }, null);
  orderedUnits$1.reduce((previous, current) => {
    if (!isUndefined(vals[current])) {
      if (previous) {
        const fraction = vals[previous] % 1;
        vals[previous] -= fraction;
        vals[current] += fraction * matrix[previous][current];
      }
      return current;
    } else {
      return previous;
    }
  }, null);
}
function removeZeroes(vals) {
  const newVals = {};
  for (const [key, value] of Object.entries(vals)) {
    if (value !== 0) {
      newVals[key] = value;
    }
  }
  return newVals;
}
var Duration = class _Duration {
  /**
   * @private
   */
  constructor(config2) {
    const accurate = config2.conversionAccuracy === "longterm" || false;
    let matrix = accurate ? accurateMatrix : casualMatrix;
    if (config2.matrix) {
      matrix = config2.matrix;
    }
    this.values = config2.values;
    this.loc = config2.loc || Locale.create();
    this.conversionAccuracy = accurate ? "longterm" : "casual";
    this.invalid = config2.invalid || null;
    this.matrix = matrix;
    this.isLuxonDuration = true;
  }
  /**
   * Create Duration from a number of milliseconds.
   * @param {number} count of milliseconds
   * @param {Object} opts - options for parsing
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @return {Duration}
   */
  static fromMillis(count, opts) {
    return _Duration.fromObject({ milliseconds: count }, opts);
  }
  /**
   * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.
   * If this object is empty then a zero milliseconds duration is returned.
   * @param {Object} obj - the object to create the DateTime from
   * @param {number} obj.years
   * @param {number} obj.quarters
   * @param {number} obj.months
   * @param {number} obj.weeks
   * @param {number} obj.days
   * @param {number} obj.hours
   * @param {number} obj.minutes
   * @param {number} obj.seconds
   * @param {number} obj.milliseconds
   * @param {Object} [opts=[]] - options for creating this Duration
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
   * @param {string} [opts.matrix=Object] - the custom conversion system to use
   * @return {Duration}
   */
  static fromObject(obj, opts = {}) {
    if (obj == null || typeof obj !== "object") {
      throw new InvalidArgumentError(
        `Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}`
      );
    }
    return new _Duration({
      values: normalizeObject(obj, _Duration.normalizeUnit),
      loc: Locale.fromObject(opts),
      conversionAccuracy: opts.conversionAccuracy,
      matrix: opts.matrix
    });
  }
  /**
   * Create a Duration from DurationLike.
   *
   * @param {Object | number | Duration} durationLike
   * One of:
   * - object with keys like 'years' and 'hours'.
   * - number representing milliseconds
   * - Duration instance
   * @return {Duration}
   */
  static fromDurationLike(durationLike) {
    if (isNumber(durationLike)) {
      return _Duration.fromMillis(durationLike);
    } else if (_Duration.isDuration(durationLike)) {
      return durationLike;
    } else if (typeof durationLike === "object") {
      return _Duration.fromObject(durationLike);
    } else {
      throw new InvalidArgumentError(
        `Unknown duration argument ${durationLike} of type ${typeof durationLike}`
      );
    }
  }
  /**
   * Create a Duration from an ISO 8601 duration string.
   * @param {string} text - text to parse
   * @param {Object} opts - options for parsing
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
   * @param {string} [opts.matrix=Object] - the preset conversion system to use
   * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
   * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
   * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }
   * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }
   * @return {Duration}
   */
  static fromISO(text, opts) {
    const [parsed] = parseISODuration(text);
    if (parsed) {
      return _Duration.fromObject(parsed, opts);
    } else {
      return _Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
    }
  }
  /**
   * Create a Duration from an ISO 8601 time string.
   * @param {string} text - text to parse
   * @param {Object} opts - options for parsing
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
   * @param {string} [opts.matrix=Object] - the conversion system to use
   * @see https://en.wikipedia.org/wiki/ISO_8601#Times
   * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }
   * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @return {Duration}
   */
  static fromISOTime(text, opts) {
    const [parsed] = parseISOTimeOnly(text);
    if (parsed) {
      return _Duration.fromObject(parsed, opts);
    } else {
      return _Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
    }
  }
  /**
   * Create an invalid Duration.
   * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent
   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
   * @return {Duration}
   */
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidDurationError(invalid);
    } else {
      return new _Duration({ invalid });
    }
  }
  /**
   * @private
   */
  static normalizeUnit(unit3) {
    const normalized = {
      year: "years",
      years: "years",
      quarter: "quarters",
      quarters: "quarters",
      month: "months",
      months: "months",
      week: "weeks",
      weeks: "weeks",
      day: "days",
      days: "days",
      hour: "hours",
      hours: "hours",
      minute: "minutes",
      minutes: "minutes",
      second: "seconds",
      seconds: "seconds",
      millisecond: "milliseconds",
      milliseconds: "milliseconds"
    }[unit3 ? unit3.toLowerCase() : unit3];
    if (!normalized) throw new InvalidUnitError(unit3);
    return normalized;
  }
  /**
   * Check if an object is a Duration. Works across context boundaries
   * @param {object} o
   * @return {boolean}
   */
  static isDuration(o) {
    return o && o.isLuxonDuration || false;
  }
  /**
   * Get  the locale of a Duration, such 'en-GB'
   * @type {string}
   */
  get locale() {
    return this.isValid ? this.loc.locale : null;
  }
  /**
   * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration
   *
   * @type {string}
   */
  get numberingSystem() {
    return this.isValid ? this.loc.numberingSystem : null;
  }
  /**
   * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:
   * * `S` for milliseconds
   * * `s` for seconds
   * * `m` for minutes
   * * `h` for hours
   * * `d` for days
   * * `w` for weeks
   * * `M` for months
   * * `y` for years
   * Notes:
   * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits
   * * Tokens can be escaped by wrapping with single quotes.
   * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.
   * @param {string} fmt - the format string
   * @param {Object} opts - options
   * @param {boolean} [opts.floor=true] - floor numerical values
   * @param {'negative'|'all'|'negativeLargestOnly'} [opts.signMode=negative] - How to handle signs
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2"
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002"
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000"
   * @example Duration.fromObject({ days: 6, seconds: 2 }).toFormat("d s", { signMode: "all" }) //=> "+6 +2"
   * @example Duration.fromObject({ days: -6, seconds: -2 }).toFormat("d s", { signMode: "all" }) //=> "-6 -2"
   * @example Duration.fromObject({ days: -6, seconds: -2 }).toFormat("d s", { signMode: "negativeLargestOnly" }) //=> "-6 2"
   * @return {string}
   */
  toFormat(fmt, opts = {}) {
    const fmtOpts = {
      ...opts,
      floor: opts.round !== false && opts.floor !== false
    };
    return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2;
  }
  /**
   * Returns a string representation of a Duration with all units included.
   * To modify its behavior, use `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options
   * @param {Object} opts - Formatting options. Accepts the same keys as the options parameter of the native `Intl.NumberFormat` constructor, as well as `listStyle`.
   * @param {string} [opts.listStyle='narrow'] - How to format the merged list. Corresponds to the `style` property of the options parameter of the native `Intl.ListFormat` constructor.
   * @param {boolean} [opts.showZeros=true] - Show all units previously used by the duration even if they are zero
   * @example
   * ```js
   * var dur = Duration.fromObject({ months: 1, weeks: 0, hours: 5, minutes: 6 })
   * dur.toHuman() //=> '1 month, 0 weeks, 5 hours, 6 minutes'
   * dur.toHuman({ listStyle: "long" }) //=> '1 month, 0 weeks, 5 hours, and 6 minutes'
   * dur.toHuman({ unitDisplay: "short" }) //=> '1 mth, 0 wks, 5 hr, 6 min'
   * dur.toHuman({ showZeros: false }) //=> '1 month, 5 hours, 6 minutes'
   * ```
   */
  toHuman(opts = {}) {
    if (!this.isValid) return INVALID$2;
    const showZeros = opts.showZeros !== false;
    const l2 = orderedUnits$1.map((unit3) => {
      const val = this.values[unit3];
      if (isUndefined(val) || val === 0 && !showZeros) {
        return null;
      }
      return this.loc.numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit3.slice(0, -1) }).format(val);
    }).filter((n2) => n2);
    return this.loc.listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts }).format(l2);
  }
  /**
   * Returns a JavaScript object with this Duration's values.
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }
   * @return {Object}
   */
  toObject() {
    if (!this.isValid) return {};
    return { ...this.values };
  }
  /**
   * Returns an ISO 8601-compliant string representation of this Duration.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
   * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'
   * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'
   * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'
   * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'
   * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'
   * @return {string}
   */
  toISO() {
    if (!this.isValid) return null;
    let s2 = "P";
    if (this.years !== 0) s2 += this.years + "Y";
    if (this.months !== 0 || this.quarters !== 0) s2 += this.months + this.quarters * 3 + "M";
    if (this.weeks !== 0) s2 += this.weeks + "W";
    if (this.days !== 0) s2 += this.days + "D";
    if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)
      s2 += "T";
    if (this.hours !== 0) s2 += this.hours + "H";
    if (this.minutes !== 0) s2 += this.minutes + "M";
    if (this.seconds !== 0 || this.milliseconds !== 0)
      s2 += roundTo(this.seconds + this.milliseconds / 1e3, 3) + "S";
    if (s2 === "P") s2 += "T0S";
    return s2;
  }
  /**
   * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.
   * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Times
   * @param {Object} opts - options
   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
   * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'
   * @return {string}
   */
  toISOTime(opts = {}) {
    if (!this.isValid) return null;
    const millis = this.toMillis();
    if (millis < 0 || millis >= 864e5) return null;
    opts = {
      suppressMilliseconds: false,
      suppressSeconds: false,
      includePrefix: false,
      format: "extended",
      ...opts,
      includeOffset: false
    };
    const dateTime = DateTime.fromMillis(millis, { zone: "UTC" });
    return dateTime.toISOTime(opts);
  }
  /**
   * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.
   * @return {string}
   */
  toJSON() {
    return this.toISO();
  }
  /**
   * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.
   * @return {string}
   */
  toString() {
    return this.toISO();
  }
  /**
   * Returns a string representation of this Duration appropriate for the REPL.
   * @return {string}
   */
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
    if (this.isValid) {
      return `Duration { values: ${JSON.stringify(this.values)} }`;
    } else {
      return `Duration { Invalid, reason: ${this.invalidReason} }`;
    }
  }
  /**
   * Returns an milliseconds value of this Duration.
   * @return {number}
   */
  toMillis() {
    if (!this.isValid) return NaN;
    return durationToMillis(this.matrix, this.values);
  }
  /**
   * Returns an milliseconds value of this Duration. Alias of {@link toMillis}
   * @return {number}
   */
  valueOf() {
    return this.toMillis();
  }
  /**
   * Make this Duration longer by the specified amount. Return a newly-constructed Duration.
   * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   * @return {Duration}
   */
  plus(duration3) {
    if (!this.isValid) return this;
    const dur = _Duration.fromDurationLike(duration3), result = {};
    for (const k of orderedUnits$1) {
      if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {
        result[k] = dur.get(k) + this.get(k);
      }
    }
    return clone$1(this, { values: result }, true);
  }
  /**
   * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
   * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   * @return {Duration}
   */
  minus(duration3) {
    if (!this.isValid) return this;
    const dur = _Duration.fromDurationLike(duration3);
    return this.plus(dur.negate());
  }
  /**
   * Scale this Duration by the specified amount. Return a newly-constructed Duration.
   * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.
   * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }
   * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 }
   * @return {Duration}
   */
  mapUnits(fn) {
    if (!this.isValid) return this;
    const result = {};
    for (const k of Object.keys(this.values)) {
      result[k] = asNumber(fn(this.values[k], k));
    }
    return clone$1(this, { values: result }, true);
  }
  /**
   * Get the value of unit.
   * @param {string} unit - a unit such as 'minute' or 'day'
   * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2
   * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0
   * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3
   * @return {number}
   */
  get(unit3) {
    return this[_Duration.normalizeUnit(unit3)];
  }
  /**
   * "Set" the values of specified units. Return a newly-constructed Duration.
   * @param {Object} values - a mapping of units to numbers
   * @example dur.set({ years: 2017 })
   * @example dur.set({ hours: 8, minutes: 30 })
   * @return {Duration}
   */
  set(values) {
    if (!this.isValid) return this;
    const mixed = { ...this.values, ...normalizeObject(values, _Duration.normalizeUnit) };
    return clone$1(this, { values: mixed });
  }
  /**
   * "Set" the locale and/or numberingSystem.  Returns a newly-constructed Duration.
   * @example dur.reconfigure({ locale: 'en-GB' })
   * @return {Duration}
   */
  reconfigure({ locale: locale3, numberingSystem, conversionAccuracy, matrix } = {}) {
    const loc = this.loc.clone({ locale: locale3, numberingSystem });
    const opts = { loc, matrix, conversionAccuracy };
    return clone$1(this, opts);
  }
  /**
   * Return the length of the duration in the specified unit.
   * @param {string} unit - a unit such as 'minutes' or 'days'
   * @example Duration.fromObject({years: 1}).as('days') //=> 365
   * @example Duration.fromObject({years: 1}).as('months') //=> 12
   * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5
   * @return {number}
   */
  as(unit3) {
    return this.isValid ? this.shiftTo(unit3).get(unit3) : NaN;
  }
  /**
   * Reduce this Duration to its canonical representation in its current units.
   * Assuming the overall value of the Duration is positive, this means:
   * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example)
   * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise
   *   the overall value would be negative, see third example)
   * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example)
   *
   * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`.
   * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }
   * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 }
   * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }
   * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 }
   * @return {Duration}
   */
  normalize() {
    if (!this.isValid) return this;
    const vals = this.toObject();
    normalizeValues(this.matrix, vals);
    return clone$1(this, { values: vals }, true);
  }
  /**
   * Rescale units to its largest representation
   * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 }
   * @return {Duration}
   */
  rescale() {
    if (!this.isValid) return this;
    const vals = removeZeroes(this.normalize().shiftToAll().toObject());
    return clone$1(this, { values: vals }, true);
  }
  /**
   * Convert this Duration into its representation in a different set of units.
   * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }
   * @return {Duration}
   */
  shiftTo(...units) {
    if (!this.isValid) return this;
    if (units.length === 0) {
      return this;
    }
    units = units.map((u) => _Duration.normalizeUnit(u));
    const built = {}, accumulated = {}, vals = this.toObject();
    let lastUnit;
    for (const k of orderedUnits$1) {
      if (units.indexOf(k) >= 0) {
        lastUnit = k;
        let own = 0;
        for (const ak in accumulated) {
          own += this.matrix[ak][k] * accumulated[ak];
          accumulated[ak] = 0;
        }
        if (isNumber(vals[k])) {
          own += vals[k];
        }
        const i = Math.trunc(own);
        built[k] = i;
        accumulated[k] = (own * 1e3 - i * 1e3) / 1e3;
      } else if (isNumber(vals[k])) {
        accumulated[k] = vals[k];
      }
    }
    for (const key in accumulated) {
      if (accumulated[key] !== 0) {
        built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
      }
    }
    normalizeValues(this.matrix, built);
    return clone$1(this, { values: built }, true);
  }
  /**
   * Shift this Duration to all available units.
   * Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds")
   * @return {Duration}
   */
  shiftToAll() {
    if (!this.isValid) return this;
    return this.shiftTo(
      "years",
      "months",
      "weeks",
      "days",
      "hours",
      "minutes",
      "seconds",
      "milliseconds"
    );
  }
  /**
   * Return the negative of this Duration.
   * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }
   * @return {Duration}
   */
  negate() {
    if (!this.isValid) return this;
    const negated = {};
    for (const k of Object.keys(this.values)) {
      negated[k] = this.values[k] === 0 ? 0 : -this.values[k];
    }
    return clone$1(this, { values: negated }, true);
  }
  /**
   * Removes all units with values equal to 0 from this Duration.
   * @example Duration.fromObject({ years: 2, days: 0, hours: 0, minutes: 0 }).removeZeros().toObject() //=> { years: 2 }
   * @return {Duration}
   */
  removeZeros() {
    if (!this.isValid) return this;
    const vals = removeZeroes(this.values);
    return clone$1(this, { values: vals }, true);
  }
  /**
   * Get the years.
   * @type {number}
   */
  get years() {
    return this.isValid ? this.values.years || 0 : NaN;
  }
  /**
   * Get the quarters.
   * @type {number}
   */
  get quarters() {
    return this.isValid ? this.values.quarters || 0 : NaN;
  }
  /**
   * Get the months.
   * @type {number}
   */
  get months() {
    return this.isValid ? this.values.months || 0 : NaN;
  }
  /**
   * Get the weeks
   * @type {number}
   */
  get weeks() {
    return this.isValid ? this.values.weeks || 0 : NaN;
  }
  /**
   * Get the days.
   * @type {number}
   */
  get days() {
    return this.isValid ? this.values.days || 0 : NaN;
  }
  /**
   * Get the hours.
   * @type {number}
   */
  get hours() {
    return this.isValid ? this.values.hours || 0 : NaN;
  }
  /**
   * Get the minutes.
   * @type {number}
   */
  get minutes() {
    return this.isValid ? this.values.minutes || 0 : NaN;
  }
  /**
   * Get the seconds.
   * @return {number}
   */
  get seconds() {
    return this.isValid ? this.values.seconds || 0 : NaN;
  }
  /**
   * Get the milliseconds.
   * @return {number}
   */
  get milliseconds() {
    return this.isValid ? this.values.milliseconds || 0 : NaN;
  }
  /**
   * Returns whether the Duration is invalid. Invalid durations are returned by diff operations
   * on invalid DateTimes or Intervals.
   * @return {boolean}
   */
  get isValid() {
    return this.invalid === null;
  }
  /**
   * Returns an error code if this Duration became invalid, or null if the Duration is valid
   * @return {string}
   */
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  /**
   * Returns an explanation of why this Duration became invalid, or null if the Duration is valid
   * @type {string}
   */
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  /**
   * Equality check
   * Two Durations are equal iff they have the same units and the same values for each unit.
   * @param {Duration} other
   * @return {boolean}
   */
  equals(other) {
    if (!this.isValid || !other.isValid) {
      return false;
    }
    if (!this.loc.equals(other.loc)) {
      return false;
    }
    function eq(v1, v2) {
      if (v1 === void 0 || v1 === 0) return v2 === void 0 || v2 === 0;
      return v1 === v2;
    }
    for (const u of orderedUnits$1) {
      if (!eq(this.values[u], other.values[u])) {
        return false;
      }
    }
    return true;
  }
};
var INVALID$1 = "Invalid Interval";
function validateStartEnd(start2, end) {
  if (!start2 || !start2.isValid) {
    return Interval.invalid("missing or invalid start");
  } else if (!end || !end.isValid) {
    return Interval.invalid("missing or invalid end");
  } else if (end < start2) {
    return Interval.invalid(
      "end before start",
      `The end of an interval must be after its start, but you had start=${start2.toISO()} and end=${end.toISO()}`
    );
  } else {
    return null;
  }
}
var Interval = class _Interval {
  /**
   * @private
   */
  constructor(config2) {
    this.s = config2.start;
    this.e = config2.end;
    this.invalid = config2.invalid || null;
    this.isLuxonInterval = true;
  }
  /**
   * Create an invalid Interval.
   * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent
   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
   * @return {Interval}
   */
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the Interval is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidIntervalError(invalid);
    } else {
      return new _Interval({ invalid });
    }
  }
  /**
   * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.
   * @param {DateTime|Date|Object} start
   * @param {DateTime|Date|Object} end
   * @return {Interval}
   */
  static fromDateTimes(start2, end) {
    const builtStart = friendlyDateTime(start2), builtEnd = friendlyDateTime(end);
    const validateError = validateStartEnd(builtStart, builtEnd);
    if (validateError == null) {
      return new _Interval({
        start: builtStart,
        end: builtEnd
      });
    } else {
      return validateError;
    }
  }
  /**
   * Create an Interval from a start DateTime and a Duration to extend to.
   * @param {DateTime|Date|Object} start
   * @param {Duration|Object|number} duration - the length of the Interval.
   * @return {Interval}
   */
  static after(start2, duration3) {
    const dur = Duration.fromDurationLike(duration3), dt = friendlyDateTime(start2);
    return _Interval.fromDateTimes(dt, dt.plus(dur));
  }
  /**
   * Create an Interval from an end DateTime and a Duration to extend backwards to.
   * @param {DateTime|Date|Object} end
   * @param {Duration|Object|number} duration - the length of the Interval.
   * @return {Interval}
   */
  static before(end, duration3) {
    const dur = Duration.fromDurationLike(duration3), dt = friendlyDateTime(end);
    return _Interval.fromDateTimes(dt.minus(dur), dt);
  }
  /**
   * Create an Interval from an ISO 8601 string.
   * Accepts `<start>/<end>`, `<start>/<duration>`, and `<duration>/<end>` formats.
   * @param {string} text - the ISO string to parse
   * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @return {Interval}
   */
  static fromISO(text, opts) {
    const [s2, e] = (text || "").split("/", 2);
    if (s2 && e) {
      let start2, startIsValid;
      try {
        start2 = DateTime.fromISO(s2, opts);
        startIsValid = start2.isValid;
      } catch (e3) {
        startIsValid = false;
      }
      let end, endIsValid;
      try {
        end = DateTime.fromISO(e, opts);
        endIsValid = end.isValid;
      } catch (e3) {
        endIsValid = false;
      }
      if (startIsValid && endIsValid) {
        return _Interval.fromDateTimes(start2, end);
      }
      if (startIsValid) {
        const dur = Duration.fromISO(e, opts);
        if (dur.isValid) {
          return _Interval.after(start2, dur);
        }
      } else if (endIsValid) {
        const dur = Duration.fromISO(s2, opts);
        if (dur.isValid) {
          return _Interval.before(end, dur);
        }
      }
    }
    return _Interval.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
  }
  /**
   * Check if an object is an Interval. Works across context boundaries
   * @param {object} o
   * @return {boolean}
   */
  static isInterval(o) {
    return o && o.isLuxonInterval || false;
  }
  /**
   * Returns the start of the Interval
   * @type {DateTime}
   */
  get start() {
    return this.isValid ? this.s : null;
  }
  /**
   * Returns the end of the Interval. This is the first instant which is not part of the interval
   * (Interval is half-open).
   * @type {DateTime}
   */
  get end() {
    return this.isValid ? this.e : null;
  }
  /**
   * Returns the last DateTime included in the interval (since end is not part of the interval)
   * @type {DateTime}
   */
  get lastDateTime() {
    return this.isValid ? this.e ? this.e.minus(1) : null : null;
  }
  /**
   * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.
   * @type {boolean}
   */
  get isValid() {
    return this.invalidReason === null;
  }
  /**
   * Returns an error code if this Interval is invalid, or null if the Interval is valid
   * @type {string}
   */
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  /**
   * Returns an explanation of why this Interval became invalid, or null if the Interval is valid
   * @type {string}
   */
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  /**
   * Returns the length of the Interval in the specified unit.
   * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.
   * @return {number}
   */
  length(unit3 = "milliseconds") {
    return this.isValid ? this.toDuration(...[unit3]).get(unit3) : NaN;
  }
  /**
   * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.
   * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'
   * asks 'what dates are included in this interval?', not 'how many days long is this interval?'
   * @param {string} [unit='milliseconds'] - the unit of time to count.
   * @param {Object} opts - options
   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; this operation will always use the locale of the start DateTime
   * @return {number}
   */
  count(unit3 = "milliseconds", opts) {
    if (!this.isValid) return NaN;
    const start2 = this.start.startOf(unit3, opts);
    let end;
    if (opts?.useLocaleWeeks) {
      end = this.end.reconfigure({ locale: start2.locale });
    } else {
      end = this.end;
    }
    end = end.startOf(unit3, opts);
    return Math.floor(end.diff(start2, unit3).get(unit3)) + (end.valueOf() !== this.end.valueOf());
  }
  /**
   * Returns whether this Interval's start and end are both in the same unit of time
   * @param {string} unit - the unit of time to check sameness on
   * @return {boolean}
   */
  hasSame(unit3) {
    return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit3) : false;
  }
  /**
   * Return whether this Interval has the same start and end DateTimes.
   * @return {boolean}
   */
  isEmpty() {
    return this.s.valueOf() === this.e.valueOf();
  }
  /**
   * Return whether this Interval's start is after the specified DateTime.
   * @param {DateTime} dateTime
   * @return {boolean}
   */
  isAfter(dateTime) {
    if (!this.isValid) return false;
    return this.s > dateTime;
  }
  /**
   * Return whether this Interval's end is before the specified DateTime.
   * @param {DateTime} dateTime
   * @return {boolean}
   */
  isBefore(dateTime) {
    if (!this.isValid) return false;
    return this.e <= dateTime;
  }
  /**
   * Return whether this Interval contains the specified DateTime.
   * @param {DateTime} dateTime
   * @return {boolean}
   */
  contains(dateTime) {
    if (!this.isValid) return false;
    return this.s <= dateTime && this.e > dateTime;
  }
  /**
   * "Sets" the start and/or end dates. Returns a newly-constructed Interval.
   * @param {Object} values - the values to set
   * @param {DateTime} values.start - the starting DateTime
   * @param {DateTime} values.end - the ending DateTime
   * @return {Interval}
   */
  set({ start: start2, end } = {}) {
    if (!this.isValid) return this;
    return _Interval.fromDateTimes(start2 || this.s, end || this.e);
  }
  /**
   * Split this Interval at each of the specified DateTimes
   * @param {...DateTime} dateTimes - the unit of time to count.
   * @return {Array}
   */
  splitAt(...dateTimes) {
    if (!this.isValid) return [];
    const sorted = dateTimes.map(friendlyDateTime).filter((d) => this.contains(d)).sort((a, b) => a.toMillis() - b.toMillis()), results = [];
    let { s: s2 } = this, i = 0;
    while (s2 < this.e) {
      const added = sorted[i] || this.e, next = +added > +this.e ? this.e : added;
      results.push(_Interval.fromDateTimes(s2, next));
      s2 = next;
      i += 1;
    }
    return results;
  }
  /**
   * Split this Interval into smaller Intervals, each of the specified length.
   * Left over time is grouped into a smaller interval
   * @param {Duration|Object|number} duration - The length of each resulting interval.
   * @return {Array}
   */
  splitBy(duration3) {
    const dur = Duration.fromDurationLike(duration3);
    if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) {
      return [];
    }
    let { s: s2 } = this, idx = 1, next;
    const results = [];
    while (s2 < this.e) {
      const added = this.start.plus(dur.mapUnits((x2) => x2 * idx));
      next = +added > +this.e ? this.e : added;
      results.push(_Interval.fromDateTimes(s2, next));
      s2 = next;
      idx += 1;
    }
    return results;
  }
  /**
   * Split this Interval into the specified number of smaller intervals.
   * @param {number} numberOfParts - The number of Intervals to divide the Interval into.
   * @return {Array}
   */
  divideEqually(numberOfParts) {
    if (!this.isValid) return [];
    return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);
  }
  /**
   * Return whether this Interval overlaps with the specified Interval
   * @param {Interval} other
   * @return {boolean}
   */
  overlaps(other) {
    return this.e > other.s && this.s < other.e;
  }
  /**
   * Return whether this Interval's end is adjacent to the specified Interval's start.
   * @param {Interval} other
   * @return {boolean}
   */
  abutsStart(other) {
    if (!this.isValid) return false;
    return +this.e === +other.s;
  }
  /**
   * Return whether this Interval's start is adjacent to the specified Interval's end.
   * @param {Interval} other
   * @return {boolean}
   */
  abutsEnd(other) {
    if (!this.isValid) return false;
    return +other.e === +this.s;
  }
  /**
   * Returns true if this Interval fully contains the specified Interval, specifically if the intersect (of this Interval and the other Interval) is equal to the other Interval; false otherwise.
   * @param {Interval} other
   * @return {boolean}
   */
  engulfs(other) {
    if (!this.isValid) return false;
    return this.s <= other.s && this.e >= other.e;
  }
  /**
   * Return whether this Interval has the same start and end as the specified Interval.
   * @param {Interval} other
   * @return {boolean}
   */
  equals(other) {
    if (!this.isValid || !other.isValid) {
      return false;
    }
    return this.s.equals(other.s) && this.e.equals(other.e);
  }
  /**
   * Return an Interval representing the intersection of this Interval and the specified Interval.
   * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.
   * Returns null if the intersection is empty, meaning, the intervals don't intersect.
   * @param {Interval} other
   * @return {Interval}
   */
  intersection(other) {
    if (!this.isValid) return this;
    const s2 = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e;
    if (s2 >= e) {
      return null;
    } else {
      return _Interval.fromDateTimes(s2, e);
    }
  }
  /**
   * Return an Interval representing the union of this Interval and the specified Interval.
   * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.
   * @param {Interval} other
   * @return {Interval}
   */
  union(other) {
    if (!this.isValid) return this;
    const s2 = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e;
    return _Interval.fromDateTimes(s2, e);
  }
  /**
   * Merge an array of Intervals into an equivalent minimal set of Intervals.
   * Combines overlapping and adjacent Intervals.
   * The resulting array will contain the Intervals in ascending order, that is, starting with the earliest Interval
   * and ending with the latest.
   *
   * @param {Array} intervals
   * @return {Array}
   */
  static merge(intervals) {
    const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce(
      ([sofar, current], item) => {
        if (!current) {
          return [sofar, item];
        } else if (current.overlaps(item) || current.abutsStart(item)) {
          return [sofar, current.union(item)];
        } else {
          return [sofar.concat([current]), item];
        }
      },
      [[], null]
    );
    if (final) {
      found.push(final);
    }
    return found;
  }
  /**
   * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.
   * @param {Array} intervals
   * @return {Array}
   */
  static xor(intervals) {
    let start2 = null, currentCount = 0;
    const results = [], ends = intervals.map((i) => [
      { time: i.s, type: "s" },
      { time: i.e, type: "e" }
    ]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a, b) => a.time - b.time);
    for (const i of arr) {
      currentCount += i.type === "s" ? 1 : -1;
      if (currentCount === 1) {
        start2 = i.time;
      } else {
        if (start2 && +start2 !== +i.time) {
          results.push(_Interval.fromDateTimes(start2, i.time));
        }
        start2 = null;
      }
    }
    return _Interval.merge(results);
  }
  /**
   * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.
   * @param {...Interval} intervals
   * @return {Array}
   */
  difference(...intervals) {
    return _Interval.xor([this].concat(intervals)).map((i) => this.intersection(i)).filter((i) => i && !i.isEmpty());
  }
  /**
   * Returns a string representation of this Interval appropriate for debugging.
   * @return {string}
   */
  toString() {
    if (!this.isValid) return INVALID$1;
    return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`;
  }
  /**
   * Returns a string representation of this Interval appropriate for the REPL.
   * @return {string}
   */
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
    if (this.isValid) {
      return `Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`;
    } else {
      return `Interval { Invalid, reason: ${this.invalidReason} }`;
    }
  }
  /**
   * Returns a localized string representing this Interval. Accepts the same options as the
   * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as
   * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method
   * is browser-specific, but in general it will return an appropriate representation of the
   * Interval in the assigned locale. Defaults to the system's locale if no locale has been
   * specified.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
   * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or
   * Intl.DateTimeFormat constructor options.
   * @param {Object} opts - Options to override the configuration of the start DateTime.
   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022
   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022
   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022
   * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM
   * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p
   * @return {string}
   */
  toLocaleString(formatOpts = DATE_SHORT, opts = {}) {
    return this.isValid ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID$1;
  }
  /**
   * Returns an ISO 8601-compliant string representation of this Interval.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @param {Object} opts - The same options as {@link DateTime#toISO}
   * @return {string}
   */
  toISO(opts) {
    if (!this.isValid) return INVALID$1;
    return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;
  }
  /**
   * Returns an ISO 8601-compliant string representation of date of this Interval.
   * The time components are ignored.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @return {string}
   */
  toISODate() {
    if (!this.isValid) return INVALID$1;
    return `${this.s.toISODate()}/${this.e.toISODate()}`;
  }
  /**
   * Returns an ISO 8601-compliant string representation of time of this Interval.
   * The date components are ignored.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @param {Object} opts - The same options as {@link DateTime#toISO}
   * @return {string}
   */
  toISOTime(opts) {
    if (!this.isValid) return INVALID$1;
    return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;
  }
  /**
   * Returns a string representation of this Interval formatted according to the specified format
   * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible
   * formatting tool.
   * @param {string} dateFormat - The format string. This string formats the start and end time.
   * See {@link DateTime#toFormat} for details.
   * @param {Object} opts - Options.
   * @param {string} [opts.separator =  ' – '] - A separator to place between the start and end
   * representations.
   * @return {string}
   */
  toFormat(dateFormat, { separator = " \u2013 " } = {}) {
    if (!this.isValid) return INVALID$1;
    return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;
  }
  /**
   * Return a Duration representing the time spanned by this interval.
   * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.
   * @param {Object} opts - options that affect the creation of the Duration
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }
   * @return {Duration}
   */
  toDuration(unit3, opts) {
    if (!this.isValid) {
      return Duration.invalid(this.invalidReason);
    }
    return this.e.diff(this.s, unit3, opts);
  }
  /**
   * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes
   * @param {function} mapFn
   * @return {Interval}
   * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())
   * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))
   */
  mapEndpoints(mapFn) {
    return _Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));
  }
};
var Info = class {
  /**
   * Return whether the specified zone contains a DST.
   * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.
   * @return {boolean}
   */
  static hasDST(zone = Settings.defaultZone) {
    const proto = DateTime.now().setZone(zone).set({ month: 12 });
    return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset;
  }
  /**
   * Return whether the specified zone is a valid IANA specifier.
   * @param {string} zone - Zone to check
   * @return {boolean}
   */
  static isValidIANAZone(zone) {
    return IANAZone.isValidZone(zone);
  }
  /**
   * Converts the input into a {@link Zone} instance.
   *
   * * If `input` is already a Zone instance, it is returned unchanged.
   * * If `input` is a string containing a valid time zone name, a Zone instance
   *   with that name is returned.
   * * If `input` is a string that doesn't refer to a known time zone, a Zone
   *   instance with {@link Zone#isValid} == false is returned.
   * * If `input is a number, a Zone instance with the specified fixed offset
   *   in minutes is returned.
   * * If `input` is `null` or `undefined`, the default zone is returned.
   * @param {string|Zone|number} [input] - the value to be converted
   * @return {Zone}
   */
  static normalizeZone(input) {
    return normalizeZone(input, Settings.defaultZone);
  }
  /**
   * Get the weekday on which the week starts according to the given locale.
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @returns {number} the start of the week, 1 for Monday through 7 for Sunday
   */
  static getStartOfWeek({ locale: locale3 = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale3)).getStartOfWeek();
  }
  /**
   * Get the minimum number of days necessary in a week before it is considered part of the next year according
   * to the given locale.
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @returns {number}
   */
  static getMinimumDaysInFirstWeek({ locale: locale3 = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale3)).getMinDaysInFirstWeek();
  }
  /**
   * Get the weekdays, which are considered the weekend according to the given locale
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @returns {number[]} an array of weekdays, 1 for Monday through 7 for Sunday
   */
  static getWeekendWeekdays({ locale: locale3 = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale3)).getWeekendDays().slice();
  }
  /**
   * Return an array of standalone month names.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
   * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @param {string} [opts.outputCalendar='gregory'] - the calendar
   * @example Info.months()[0] //=> 'January'
   * @example Info.months('short')[0] //=> 'Jan'
   * @example Info.months('numeric')[0] //=> '1'
   * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'
   * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'
   * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'
   * @return {Array}
   */
  static months(length = "long", { locale: locale3 = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) {
    return (locObj || Locale.create(locale3, numberingSystem, outputCalendar)).months(length);
  }
  /**
   * Return an array of format month names.
   * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that
   * changes the string.
   * See {@link Info#months}
   * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @param {string} [opts.outputCalendar='gregory'] - the calendar
   * @return {Array}
   */
  static monthsFormat(length = "long", { locale: locale3 = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) {
    return (locObj || Locale.create(locale3, numberingSystem, outputCalendar)).months(length, true);
  }
  /**
   * Return an array of standalone week names.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
   * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long".
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @example Info.weekdays()[0] //=> 'Monday'
   * @example Info.weekdays('short')[0] //=> 'Mon'
   * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'
   * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'
   * @return {Array}
   */
  static weekdays(length = "long", { locale: locale3 = null, numberingSystem = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale3, numberingSystem, null)).weekdays(length);
  }
  /**
   * Return an array of format week names.
   * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that
   * changes the string.
   * See {@link Info#weekdays}
   * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long".
   * @param {Object} opts - options
   * @param {string} [opts.locale=null] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @return {Array}
   */
  static weekdaysFormat(length = "long", { locale: locale3 = null, numberingSystem = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale3, numberingSystem, null)).weekdays(length, true);
  }
  /**
   * Return an array of meridiems.
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @example Info.meridiems() //=> [ 'AM', 'PM' ]
   * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]
   * @return {Array}
   */
  static meridiems({ locale: locale3 = null } = {}) {
    return Locale.create(locale3).meridiems();
  }
  /**
   * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.
   * @param {string} [length='short'] - the length of the era representation, such as "short" or "long".
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @example Info.eras() //=> [ 'BC', 'AD' ]
   * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]
   * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]
   * @return {Array}
   */
  static eras(length = "short", { locale: locale3 = null } = {}) {
    return Locale.create(locale3, null, "gregory").eras(length);
  }
  /**
   * Return the set of available features in this environment.
   * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.
   * Keys:
   * * `relative`: whether this environment supports relative time formatting
   * * `localeWeek`: whether this environment supports different weekdays for the start of the week based on the locale
   * @example Info.features() //=> { relative: false, localeWeek: true }
   * @return {Object}
   */
  static features() {
    return { relative: hasRelative(), localeWeek: hasLocaleWeekInfo() };
  }
};
function dayDiff(earlier, later) {
  const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(), ms = utcDayStart(later) - utcDayStart(earlier);
  return Math.floor(Duration.fromMillis(ms).as("days"));
}
function highOrderDiffs(cursor, later, units) {
  const differs = [
    ["years", (a, b) => b.year - a.year],
    ["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4],
    ["months", (a, b) => b.month - a.month + (b.year - a.year) * 12],
    [
      "weeks",
      (a, b) => {
        const days = dayDiff(a, b);
        return (days - days % 7) / 7;
      }
    ],
    ["days", dayDiff]
  ];
  const results = {};
  const earlier = cursor;
  let lowestOrder, highWater;
  for (const [unit3, differ] of differs) {
    if (units.indexOf(unit3) >= 0) {
      lowestOrder = unit3;
      results[unit3] = differ(cursor, later);
      highWater = earlier.plus(results);
      if (highWater > later) {
        results[unit3]--;
        cursor = earlier.plus(results);
        if (cursor > later) {
          highWater = cursor;
          results[unit3]--;
          cursor = earlier.plus(results);
        }
      } else {
        cursor = highWater;
      }
    }
  }
  return [cursor, results, highWater, lowestOrder];
}
function diff(earlier, later, units, opts) {
  let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);
  const remainingMillis = later - cursor;
  const lowerOrderUnits = units.filter(
    (u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0
  );
  if (lowerOrderUnits.length === 0) {
    if (highWater < later) {
      highWater = cursor.plus({ [lowestOrder]: 1 });
    }
    if (highWater !== cursor) {
      results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);
    }
  }
  const duration3 = Duration.fromObject(results, opts);
  if (lowerOrderUnits.length > 0) {
    return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration3);
  } else {
    return duration3;
  }
}
var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support";
function intUnit(regex, post = (i) => i) {
  return { regex, deser: ([s2]) => post(parseDigits(s2)) };
}
var NBSP = String.fromCharCode(160);
var spaceOrNBSP = `[ ${NBSP}]`;
var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g");
function fixListRegex(s2) {
  return s2.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP);
}
function stripInsensitivities(s2) {
  return s2.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase();
}
function oneOf(strings, startIndex) {
  if (strings === null) {
    return null;
  } else {
    return {
      regex: RegExp(strings.map(fixListRegex).join("|")),
      deser: ([s2]) => strings.findIndex((i) => stripInsensitivities(s2) === stripInsensitivities(i)) + startIndex
    };
  }
}
function offset(regex, groups) {
  return { regex, deser: ([, h, m]) => signedOffset(h, m), groups };
}
function simple(regex) {
  return { regex, deser: ([s2]) => s2 };
}
function escapeToken(value) {
  return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
function unitForToken(token, loc) {
  const one2 = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal2 = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s2]) => s2, literal: true }), unitate = (t) => {
    if (token.literal) {
      return literal2(t);
    }
    switch (t.val) {
      // era
      case "G":
        return oneOf(loc.eras("short"), 0);
      case "GG":
        return oneOf(loc.eras("long"), 0);
      // years
      case "y":
        return intUnit(oneToSix);
      case "yy":
        return intUnit(twoToFour, untruncateYear);
      case "yyyy":
        return intUnit(four);
      case "yyyyy":
        return intUnit(fourToSix);
      case "yyyyyy":
        return intUnit(six);
      // months
      case "M":
        return intUnit(oneOrTwo);
      case "MM":
        return intUnit(two);
      case "MMM":
        return oneOf(loc.months("short", true), 1);
      case "MMMM":
        return oneOf(loc.months("long", true), 1);
      case "L":
        return intUnit(oneOrTwo);
      case "LL":
        return intUnit(two);
      case "LLL":
        return oneOf(loc.months("short", false), 1);
      case "LLLL":
        return oneOf(loc.months("long", false), 1);
      // dates
      case "d":
        return intUnit(oneOrTwo);
      case "dd":
        return intUnit(two);
      // ordinals
      case "o":
        return intUnit(oneToThree);
      case "ooo":
        return intUnit(three);
      // time
      case "HH":
        return intUnit(two);
      case "H":
        return intUnit(oneOrTwo);
      case "hh":
        return intUnit(two);
      case "h":
        return intUnit(oneOrTwo);
      case "mm":
        return intUnit(two);
      case "m":
        return intUnit(oneOrTwo);
      case "q":
        return intUnit(oneOrTwo);
      case "qq":
        return intUnit(two);
      case "s":
        return intUnit(oneOrTwo);
      case "ss":
        return intUnit(two);
      case "S":
        return intUnit(oneToThree);
      case "SSS":
        return intUnit(three);
      case "u":
        return simple(oneToNine);
      case "uu":
        return simple(oneOrTwo);
      case "uuu":
        return intUnit(one2);
      // meridiem
      case "a":
        return oneOf(loc.meridiems(), 0);
      // weekYear (k)
      case "kkkk":
        return intUnit(four);
      case "kk":
        return intUnit(twoToFour, untruncateYear);
      // weekNumber (W)
      case "W":
        return intUnit(oneOrTwo);
      case "WW":
        return intUnit(two);
      // weekdays
      case "E":
      case "c":
        return intUnit(one2);
      case "EEE":
        return oneOf(loc.weekdays("short", false), 1);
      case "EEEE":
        return oneOf(loc.weekdays("long", false), 1);
      case "ccc":
        return oneOf(loc.weekdays("short", true), 1);
      case "cccc":
        return oneOf(loc.weekdays("long", true), 1);
      // offset/zone
      case "Z":
      case "ZZ":
        return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);
      case "ZZZ":
        return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);
      // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing
      // because we don't have any way to figure out what they are
      case "z":
        return simple(/[a-z_+-/]{1,256}?/i);
      // this special-case "token" represents a place where a macro-token expanded into a white-space literal
      // in this case we accept any non-newline white-space
      case " ":
        return simple(/[^\S\n\r]/);
      default:
        return literal2(t);
    }
  };
  const unit3 = unitate(token) || {
    invalidReason: MISSING_FTP
  };
  unit3.token = token;
  return unit3;
}
var partTypeStyleToTokenVal = {
  year: {
    "2-digit": "yy",
    numeric: "yyyyy"
  },
  month: {
    numeric: "M",
    "2-digit": "MM",
    short: "MMM",
    long: "MMMM"
  },
  day: {
    numeric: "d",
    "2-digit": "dd"
  },
  weekday: {
    short: "EEE",
    long: "EEEE"
  },
  dayperiod: "a",
  dayPeriod: "a",
  hour12: {
    numeric: "h",
    "2-digit": "hh"
  },
  hour24: {
    numeric: "H",
    "2-digit": "HH"
  },
  minute: {
    numeric: "m",
    "2-digit": "mm"
  },
  second: {
    numeric: "s",
    "2-digit": "ss"
  },
  timeZoneName: {
    long: "ZZZZZ",
    short: "ZZZ"
  }
};
function tokenForPart(part, formatOpts, resolvedOpts) {
  const { type, value } = part;
  if (type === "literal") {
    const isSpace = /^\s+$/.test(value);
    return {
      literal: !isSpace,
      val: isSpace ? " " : value
    };
  }
  const style = formatOpts[type];
  let actualType = type;
  if (type === "hour") {
    if (formatOpts.hour12 != null) {
      actualType = formatOpts.hour12 ? "hour12" : "hour24";
    } else if (formatOpts.hourCycle != null) {
      if (formatOpts.hourCycle === "h11" || formatOpts.hourCycle === "h12") {
        actualType = "hour12";
      } else {
        actualType = "hour24";
      }
    } else {
      actualType = resolvedOpts.hour12 ? "hour12" : "hour24";
    }
  }
  let val = partTypeStyleToTokenVal[actualType];
  if (typeof val === "object") {
    val = val[style];
  }
  if (val) {
    return {
      literal: false,
      val
    };
  }
  return void 0;
}
function buildRegex(units) {
  const re2 = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, "");
  return [`^${re2}$`, units];
}
function match(input, regex, handlers) {
  const matches = input.match(regex);
  if (matches) {
    const all = {};
    let matchIndex = 1;
    for (const i in handlers) {
      if (hasOwnProperty(handlers, i)) {
        const h = handlers[i], groups = h.groups ? h.groups + 1 : 1;
        if (!h.literal && h.token) {
          all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));
        }
        matchIndex += groups;
      }
    }
    return [matches, all];
  } else {
    return [matches, {}];
  }
}
function dateTimeFromMatches(matches) {
  const toField = (token) => {
    switch (token) {
      case "S":
        return "millisecond";
      case "s":
        return "second";
      case "m":
        return "minute";
      case "h":
      case "H":
        return "hour";
      case "d":
        return "day";
      case "o":
        return "ordinal";
      case "L":
      case "M":
        return "month";
      case "y":
        return "year";
      case "E":
      case "c":
        return "weekday";
      case "W":
        return "weekNumber";
      case "k":
        return "weekYear";
      case "q":
        return "quarter";
      default:
        return null;
    }
  };
  let zone = null;
  let specificOffset;
  if (!isUndefined(matches.z)) {
    zone = IANAZone.create(matches.z);
  }
  if (!isUndefined(matches.Z)) {
    if (!zone) {
      zone = new FixedOffsetZone(matches.Z);
    }
    specificOffset = matches.Z;
  }
  if (!isUndefined(matches.q)) {
    matches.M = (matches.q - 1) * 3 + 1;
  }
  if (!isUndefined(matches.h)) {
    if (matches.h < 12 && matches.a === 1) {
      matches.h += 12;
    } else if (matches.h === 12 && matches.a === 0) {
      matches.h = 0;
    }
  }
  if (matches.G === 0 && matches.y) {
    matches.y = -matches.y;
  }
  if (!isUndefined(matches.u)) {
    matches.S = parseMillis(matches.u);
  }
  const vals = Object.keys(matches).reduce((r, k) => {
    const f = toField(k);
    if (f) {
      r[f] = matches[k];
    }
    return r;
  }, {});
  return [vals, zone, specificOffset];
}
var dummyDateTimeCache = null;
function getDummyDateTime() {
  if (!dummyDateTimeCache) {
    dummyDateTimeCache = DateTime.fromMillis(1555555555555);
  }
  return dummyDateTimeCache;
}
function maybeExpandMacroToken(token, locale3) {
  if (token.literal) {
    return token;
  }
  const formatOpts = Formatter.macroTokenToFormatOpts(token.val);
  const tokens = formatOptsToTokens(formatOpts, locale3);
  if (tokens == null || tokens.includes(void 0)) {
    return token;
  }
  return tokens;
}
function expandMacroTokens(tokens, locale3) {
  return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale3)));
}
var TokenParser = class {
  constructor(locale3, format2) {
    this.locale = locale3;
    this.format = format2;
    this.tokens = expandMacroTokens(Formatter.parseFormat(format2), locale3);
    this.units = this.tokens.map((t) => unitForToken(t, locale3));
    this.disqualifyingUnit = this.units.find((t) => t.invalidReason);
    if (!this.disqualifyingUnit) {
      const [regexString, handlers] = buildRegex(this.units);
      this.regex = RegExp(regexString, "i");
      this.handlers = handlers;
    }
  }
  explainFromTokens(input) {
    if (!this.isValid) {
      return { input, tokens: this.tokens, invalidReason: this.invalidReason };
    } else {
      const [rawMatches, matches] = match(input, this.regex, this.handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, void 0];
      if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) {
        throw new ConflictingSpecificationError(
          "Can't include meridiem when specifying 24-hour format"
        );
      }
      return {
        input,
        tokens: this.tokens,
        regex: this.regex,
        rawMatches,
        matches,
        result,
        zone,
        specificOffset
      };
    }
  }
  get isValid() {
    return !this.disqualifyingUnit;
  }
  get invalidReason() {
    return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null;
  }
};
function explainFromTokens(locale3, input, format2) {
  const parser = new TokenParser(locale3, format2);
  return parser.explainFromTokens(input);
}
function parseFromTokens(locale3, input, format2) {
  const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale3, input, format2);
  return [result, zone, specificOffset, invalidReason];
}
function formatOptsToTokens(formatOpts, locale3) {
  if (!formatOpts) {
    return null;
  }
  const formatter = Formatter.create(locale3, formatOpts);
  const df = formatter.dtFormatter(getDummyDateTime());
  const parts = df.formatToParts();
  const resolvedOpts = df.resolvedOptions();
  return parts.map((p) => tokenForPart(p, formatOpts, resolvedOpts));
}
var INVALID = "Invalid DateTime";
var MAX_DATE = 864e13;
function unsupportedZone(zone) {
  return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`);
}
function possiblyCachedWeekData(dt) {
  if (dt.weekData === null) {
    dt.weekData = gregorianToWeek(dt.c);
  }
  return dt.weekData;
}
function possiblyCachedLocalWeekData(dt) {
  if (dt.localWeekData === null) {
    dt.localWeekData = gregorianToWeek(
      dt.c,
      dt.loc.getMinDaysInFirstWeek(),
      dt.loc.getStartOfWeek()
    );
  }
  return dt.localWeekData;
}
function clone(inst, alts) {
  const current = {
    ts: inst.ts,
    zone: inst.zone,
    c: inst.c,
    o: inst.o,
    loc: inst.loc,
    invalid: inst.invalid
  };
  return new DateTime({ ...current, ...alts, old: current });
}
function fixOffset(localTS, o, tz) {
  let utcGuess = localTS - o * 60 * 1e3;
  const o2 = tz.offset(utcGuess);
  if (o === o2) {
    return [utcGuess, o];
  }
  utcGuess -= (o2 - o) * 60 * 1e3;
  const o3 = tz.offset(utcGuess);
  if (o2 === o3) {
    return [utcGuess, o2];
  }
  return [localTS - Math.min(o2, o3) * 60 * 1e3, Math.max(o2, o3)];
}
function tsToObj(ts, offset2) {
  ts += offset2 * 60 * 1e3;
  const d = new Date(ts);
  return {
    year: d.getUTCFullYear(),
    month: d.getUTCMonth() + 1,
    day: d.getUTCDate(),
    hour: d.getUTCHours(),
    minute: d.getUTCMinutes(),
    second: d.getUTCSeconds(),
    millisecond: d.getUTCMilliseconds()
  };
}
function objToTS(obj, offset2, zone) {
  return fixOffset(objToLocalTS(obj), offset2, zone);
}
function adjustTime(inst, dur) {
  const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = {
    ...inst.c,
    year,
    month,
    day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7
  }, millisToAdd = Duration.fromObject({
    years: dur.years - Math.trunc(dur.years),
    quarters: dur.quarters - Math.trunc(dur.quarters),
    months: dur.months - Math.trunc(dur.months),
    weeks: dur.weeks - Math.trunc(dur.weeks),
    days: dur.days - Math.trunc(dur.days),
    hours: dur.hours,
    minutes: dur.minutes,
    seconds: dur.seconds,
    milliseconds: dur.milliseconds
  }).as("milliseconds"), localTS = objToLocalTS(c);
  let [ts, o] = fixOffset(localTS, oPre, inst.zone);
  if (millisToAdd !== 0) {
    ts += millisToAdd;
    o = inst.zone.offset(ts);
  }
  return { ts, o };
}
function parseDataToDateTime(parsed, parsedZone, opts, format2, text, specificOffset) {
  const { setZone, zone } = opts;
  if (parsed && Object.keys(parsed).length !== 0 || parsedZone) {
    const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, {
      ...opts,
      zone: interpretationZone,
      specificOffset
    });
    return setZone ? inst : inst.setZone(zone);
  } else {
    return DateTime.invalid(
      new Invalid("unparsable", `the input "${text}" can't be parsed as ${format2}`)
    );
  }
}
function toTechFormat(dt, format2, allowZ = true) {
  return dt.isValid ? Formatter.create(Locale.create("en-US"), {
    allowZ,
    forceSimple: true
  }).formatDateTimeFromString(dt, format2) : null;
}
function toISODate(o, extended, precision) {
  const longFormat = o.c.year > 9999 || o.c.year < 0;
  let c = "";
  if (longFormat && o.c.year >= 0) c += "+";
  c += padStart(o.c.year, longFormat ? 6 : 4);
  if (precision === "year") return c;
  if (extended) {
    c += "-";
    c += padStart(o.c.month);
    if (precision === "month") return c;
    c += "-";
  } else {
    c += padStart(o.c.month);
    if (precision === "month") return c;
  }
  c += padStart(o.c.day);
  return c;
}
function toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision) {
  let showSeconds = !suppressSeconds || o.c.millisecond !== 0 || o.c.second !== 0, c = "";
  switch (precision) {
    case "day":
    case "month":
    case "year":
      break;
    default:
      c += padStart(o.c.hour);
      if (precision === "hour") break;
      if (extended) {
        c += ":";
        c += padStart(o.c.minute);
        if (precision === "minute") break;
        if (showSeconds) {
          c += ":";
          c += padStart(o.c.second);
        }
      } else {
        c += padStart(o.c.minute);
        if (precision === "minute") break;
        if (showSeconds) {
          c += padStart(o.c.second);
        }
      }
      if (precision === "second") break;
      if (showSeconds && (!suppressMilliseconds || o.c.millisecond !== 0)) {
        c += ".";
        c += padStart(o.c.millisecond, 3);
      }
  }
  if (includeOffset) {
    if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {
      c += "Z";
    } else if (o.o < 0) {
      c += "-";
      c += padStart(Math.trunc(-o.o / 60));
      c += ":";
      c += padStart(Math.trunc(-o.o % 60));
    } else {
      c += "+";
      c += padStart(Math.trunc(o.o / 60));
      c += ":";
      c += padStart(Math.trunc(o.o % 60));
    }
  }
  if (extendedZone) {
    c += "[" + o.zone.ianaName + "]";
  }
  return c;
}
var defaultUnitValues = {
  month: 1,
  day: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var defaultWeekUnitValues = {
  weekNumber: 1,
  weekday: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var defaultOrdinalUnitValues = {
  ordinal: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"];
var orderedWeekUnits = [
  "weekYear",
  "weekNumber",
  "weekday",
  "hour",
  "minute",
  "second",
  "millisecond"
];
var orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"];
function normalizeUnit(unit3) {
  const normalized = {
    year: "year",
    years: "year",
    month: "month",
    months: "month",
    day: "day",
    days: "day",
    hour: "hour",
    hours: "hour",
    minute: "minute",
    minutes: "minute",
    quarter: "quarter",
    quarters: "quarter",
    second: "second",
    seconds: "second",
    millisecond: "millisecond",
    milliseconds: "millisecond",
    weekday: "weekday",
    weekdays: "weekday",
    weeknumber: "weekNumber",
    weeksnumber: "weekNumber",
    weeknumbers: "weekNumber",
    weekyear: "weekYear",
    weekyears: "weekYear",
    ordinal: "ordinal"
  }[unit3.toLowerCase()];
  if (!normalized) throw new InvalidUnitError(unit3);
  return normalized;
}
function normalizeUnitWithLocalWeeks(unit3) {
  switch (unit3.toLowerCase()) {
    case "localweekday":
    case "localweekdays":
      return "localWeekday";
    case "localweeknumber":
    case "localweeknumbers":
      return "localWeekNumber";
    case "localweekyear":
    case "localweekyears":
      return "localWeekYear";
    default:
      return normalizeUnit(unit3);
  }
}
function guessOffsetForZone(zone) {
  if (zoneOffsetTs === void 0) {
    zoneOffsetTs = Settings.now();
  }
  if (zone.type !== "iana") {
    return zone.offset(zoneOffsetTs);
  }
  const zoneName = zone.name;
  let offsetGuess = zoneOffsetGuessCache.get(zoneName);
  if (offsetGuess === void 0) {
    offsetGuess = zone.offset(zoneOffsetTs);
    zoneOffsetGuessCache.set(zoneName, offsetGuess);
  }
  return offsetGuess;
}
function quickDT(obj, opts) {
  const zone = normalizeZone(opts.zone, Settings.defaultZone);
  if (!zone.isValid) {
    return DateTime.invalid(unsupportedZone(zone));
  }
  const loc = Locale.fromObject(opts);
  let ts, o;
  if (!isUndefined(obj.year)) {
    for (const u of orderedUnits) {
      if (isUndefined(obj[u])) {
        obj[u] = defaultUnitValues[u];
      }
    }
    const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
    if (invalid) {
      return DateTime.invalid(invalid);
    }
    const offsetProvis = guessOffsetForZone(zone);
    [ts, o] = objToTS(obj, offsetProvis, zone);
  } else {
    ts = Settings.now();
  }
  return new DateTime({ ts, zone, loc, o });
}
function diffRelative(start2, end, opts) {
  const round = isUndefined(opts.round) ? true : opts.round, rounding = isUndefined(opts.rounding) ? "trunc" : opts.rounding, format2 = (c, unit3) => {
    c = roundTo(c, round || opts.calendary ? 0 : 2, opts.calendary ? "round" : rounding);
    const formatter = end.loc.clone(opts).relFormatter(opts);
    return formatter.format(c, unit3);
  }, differ = (unit3) => {
    if (opts.calendary) {
      if (!end.hasSame(start2, unit3)) {
        return end.startOf(unit3).diff(start2.startOf(unit3), unit3).get(unit3);
      } else return 0;
    } else {
      return end.diff(start2, unit3).get(unit3);
    }
  };
  if (opts.unit) {
    return format2(differ(opts.unit), opts.unit);
  }
  for (const unit3 of opts.units) {
    const count = differ(unit3);
    if (Math.abs(count) >= 1) {
      return format2(count, unit3);
    }
  }
  return format2(start2 > end ? -0 : 0, opts.units[opts.units.length - 1]);
}
function lastOpts(argList) {
  let opts = {}, args;
  if (argList.length > 0 && typeof argList[argList.length - 1] === "object") {
    opts = argList[argList.length - 1];
    args = Array.from(argList).slice(0, argList.length - 1);
  } else {
    args = Array.from(argList);
  }
  return [opts, args];
}
var zoneOffsetTs;
var zoneOffsetGuessCache = /* @__PURE__ */ new Map();
var DateTime = class _DateTime {
  /**
   * @access private
   */
  constructor(config2) {
    const zone = config2.zone || Settings.defaultZone;
    let invalid = config2.invalid || (Number.isNaN(config2.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null);
    this.ts = isUndefined(config2.ts) ? Settings.now() : config2.ts;
    let c = null, o = null;
    if (!invalid) {
      const unchanged = config2.old && config2.old.ts === this.ts && config2.old.zone.equals(zone);
      if (unchanged) {
        [c, o] = [config2.old.c, config2.old.o];
      } else {
        const ot = isNumber(config2.o) && !config2.old ? config2.o : zone.offset(this.ts);
        c = tsToObj(this.ts, ot);
        invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null;
        c = invalid ? null : c;
        o = invalid ? null : ot;
      }
    }
    this._zone = zone;
    this.loc = config2.loc || Locale.create();
    this.invalid = invalid;
    this.weekData = null;
    this.localWeekData = null;
    this.c = c;
    this.o = o;
    this.isLuxonDateTime = true;
  }
  // CONSTRUCT
  /**
   * Create a DateTime for the current instant, in the system's time zone.
   *
   * Use Settings to override these default values if needed.
   * @example DateTime.now().toISO() //~> now in the ISO format
   * @return {DateTime}
   */
  static now() {
    return new _DateTime({});
  }
  /**
   * Create a local DateTime
   * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
   * @param {number} [month=1] - The month, 1-indexed
   * @param {number} [day=1] - The day of the month, 1-indexed
   * @param {number} [hour=0] - The hour of the day, in 24-hour time
   * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
   * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
   * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
   * @example DateTime.local()                                  //~> now
   * @example DateTime.local({ zone: "America/New_York" })      //~> now, in US east coast time
   * @example DateTime.local(2017)                              //~> 2017-01-01T00:00:00
   * @example DateTime.local(2017, 3)                           //~> 2017-03-01T00:00:00
   * @example DateTime.local(2017, 3, 12, { locale: "fr" })     //~> 2017-03-12T00:00:00, with a French locale
   * @example DateTime.local(2017, 3, 12, 5)                    //~> 2017-03-12T05:00:00
   * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" })   //~> 2017-03-12T05:00:00, in UTC
   * @example DateTime.local(2017, 3, 12, 5, 45)                //~> 2017-03-12T05:45:00
   * @example DateTime.local(2017, 3, 12, 5, 45, 10)            //~> 2017-03-12T05:45:10
   * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765)       //~> 2017-03-12T05:45:10.765
   * @return {DateTime}
   */
  static local() {
    const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second2, millisecond2] = args;
    return quickDT({ year, month, day, hour, minute, second: second2, millisecond: millisecond2 }, opts);
  }
  /**
   * Create a DateTime in UTC
   * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
   * @param {number} [month=1] - The month, 1-indexed
   * @param {number} [day=1] - The day of the month
   * @param {number} [hour=0] - The hour of the day, in 24-hour time
   * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
   * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
   * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
   * @param {Object} options - configuration options for the DateTime
   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
   * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance
   * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance
   * @param {string} [options.weekSettings] - the week settings to set on the resulting DateTime instance
   * @example DateTime.utc()                                              //~> now
   * @example DateTime.utc(2017)                                          //~> 2017-01-01T00:00:00Z
   * @example DateTime.utc(2017, 3)                                       //~> 2017-03-01T00:00:00Z
   * @example DateTime.utc(2017, 3, 12)                                   //~> 2017-03-12T00:00:00Z
   * @example DateTime.utc(2017, 3, 12, 5)                                //~> 2017-03-12T05:00:00Z
   * @example DateTime.utc(2017, 3, 12, 5, 45)                            //~> 2017-03-12T05:45:00Z
   * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" })          //~> 2017-03-12T05:45:00Z with a French locale
   * @example DateTime.utc(2017, 3, 12, 5, 45, 10)                        //~> 2017-03-12T05:45:10Z
   * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale
   * @return {DateTime}
   */
  static utc() {
    const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second2, millisecond2] = args;
    opts.zone = FixedOffsetZone.utcInstance;
    return quickDT({ year, month, day, hour, minute, second: second2, millisecond: millisecond2 }, opts);
  }
  /**
   * Create a DateTime from a JavaScript Date object. Uses the default zone.
   * @param {Date} date - a JavaScript Date object
   * @param {Object} options - configuration options for the DateTime
   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
   * @return {DateTime}
   */
  static fromJSDate(date6, options = {}) {
    const ts = isDate(date6) ? date6.valueOf() : NaN;
    if (Number.isNaN(ts)) {
      return _DateTime.invalid("invalid input");
    }
    const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
    if (!zoneToUse.isValid) {
      return _DateTime.invalid(unsupportedZone(zoneToUse));
    }
    return new _DateTime({
      ts,
      zone: zoneToUse,
      loc: Locale.fromObject(options)
    });
  }
  /**
   * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
   * @param {number} milliseconds - a number of milliseconds since 1970 UTC
   * @param {Object} options - configuration options for the DateTime
   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
   * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance
   * @return {DateTime}
   */
  static fromMillis(milliseconds2, options = {}) {
    if (!isNumber(milliseconds2)) {
      throw new InvalidArgumentError(
        `fromMillis requires a numerical input, but received a ${typeof milliseconds2} with value ${milliseconds2}`
      );
    } else if (milliseconds2 < -MAX_DATE || milliseconds2 > MAX_DATE) {
      return _DateTime.invalid("Timestamp out of range");
    } else {
      return new _DateTime({
        ts: milliseconds2,
        zone: normalizeZone(options.zone, Settings.defaultZone),
        loc: Locale.fromObject(options)
      });
    }
  }
  /**
   * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
   * @param {number} seconds - a number of seconds since 1970 UTC
   * @param {Object} options - configuration options for the DateTime
   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
   * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance
   * @return {DateTime}
   */
  static fromSeconds(seconds2, options = {}) {
    if (!isNumber(seconds2)) {
      throw new InvalidArgumentError("fromSeconds requires a numerical input");
    } else {
      return new _DateTime({
        ts: seconds2 * 1e3,
        zone: normalizeZone(options.zone, Settings.defaultZone),
        loc: Locale.fromObject(options)
      });
    }
  }
  /**
   * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.
   * @param {Object} obj - the object to create the DateTime from
   * @param {number} obj.year - a year, such as 1987
   * @param {number} obj.month - a month, 1-12
   * @param {number} obj.day - a day of the month, 1-31, depending on the month
   * @param {number} obj.ordinal - day of the year, 1-365 or 366
   * @param {number} obj.weekYear - an ISO week year
   * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
   * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
   * @param {number} obj.localWeekYear - a week year, according to the locale
   * @param {number} obj.localWeekNumber - a week number, between 1 and 52 or 53, depending on the year, according to the locale
   * @param {number} obj.localWeekday - a weekday, 1-7, where 1 is the first and 7 is the last day of the week, according to the locale
   * @param {number} obj.hour - hour of the day, 0-23
   * @param {number} obj.minute - minute of the hour, 0-59
   * @param {number} obj.second - second of the minute, 0-59
   * @param {number} obj.millisecond - millisecond of the second, 0-999
   * @param {Object} opts - options for creating this DateTime
   * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
   * @param {string} [opts.locale='system\'s locale'] - a locale to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
   * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
   * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })
   * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
   * @example DateTime.fromObject({ localWeekYear: 2022, localWeekNumber: 1, localWeekday: 1 }, { locale: "en-US" }).toISODate() //=> '2021-12-26'
   * @return {DateTime}
   */
  static fromObject(obj, opts = {}) {
    obj = obj || {};
    const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);
    if (!zoneToUse.isValid) {
      return _DateTime.invalid(unsupportedZone(zoneToUse));
    }
    const loc = Locale.fromObject(opts);
    const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks);
    const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, loc);
    const tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber;
    if ((containsGregor || containsOrdinal) && definiteWeekDef) {
      throw new ConflictingSpecificationError(
        "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
      );
    }
    if (containsGregorMD && containsOrdinal) {
      throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
    }
    const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor;
    let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis);
    if (useWeekData) {
      units = orderedWeekUnits;
      defaultValues = defaultWeekUnitValues;
      objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek);
    } else if (containsOrdinal) {
      units = orderedOrdinalUnits;
      defaultValues = defaultOrdinalUnitValues;
      objNow = gregorianToOrdinal(objNow);
    } else {
      units = orderedUnits;
      defaultValues = defaultUnitValues;
    }
    let foundFirst = false;
    for (const u of units) {
      const v = normalized[u];
      if (!isUndefined(v)) {
        foundFirst = true;
      } else if (foundFirst) {
        normalized[u] = defaultValues[u];
      } else {
        normalized[u] = objNow[u];
      }
    }
    const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized);
    if (invalid) {
      return _DateTime.invalid(invalid);
    }
    const gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new _DateTime({
      ts: tsFinal,
      zone: zoneToUse,
      o: offsetFinal,
      loc
    });
    if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
      return _DateTime.invalid(
        "mismatched weekday",
        `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`
      );
    }
    if (!inst.isValid) {
      return _DateTime.invalid(inst.invalid);
    }
    return inst;
  }
  /**
   * Create a DateTime from an ISO 8601 string
   * @param {string} text - the ISO string
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
   * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
   * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance
   * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance
   * @param {string} [opts.weekSettings] - the week settings to set on the resulting DateTime instance
   * @example DateTime.fromISO('2016-05-25T09:08:34.123')
   * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
   * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
   * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
   * @example DateTime.fromISO('2016-W05-4')
   * @return {DateTime}
   */
  static fromISO(text, opts = {}) {
    const [vals, parsedZone] = parseISODate(text);
    return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text);
  }
  /**
   * Create a DateTime from an RFC 2822 string
   * @param {string} text - the RFC 2822 string
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
   * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
   * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
   * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')
   * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
   * @return {DateTime}
   */
  static fromRFC2822(text, opts = {}) {
    const [vals, parsedZone] = parseRFC2822Date(text);
    return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text);
  }
  /**
   * Create a DateTime from an HTTP header date
   * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
   * @param {string} text - the HTTP header date
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
   * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
   * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
   * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
   * @example DateTime.fromHTTP('Sun Nov  6 08:49:37 1994')
   * @return {DateTime}
   */
  static fromHTTP(text, opts = {}) {
    const [vals, parsedZone] = parseHTTPDate(text);
    return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts);
  }
  /**
   * Create a DateTime from an input string and format string.
   * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).
   * @param {string} text - the string to parse
   * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
   * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
   * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @return {DateTime}
   */
  static fromFormat(text, fmt, opts = {}) {
    if (isUndefined(text) || isUndefined(fmt)) {
      throw new InvalidArgumentError("fromFormat requires an input string and a format");
    }
    const { locale: locale3 = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({
      locale: locale3,
      numberingSystem,
      defaultToEN: true
    }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);
    if (invalid) {
      return _DateTime.invalid(invalid);
    } else {
      return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);
    }
  }
  /**
   * @deprecated use fromFormat instead
   */
  static fromString(text, fmt, opts = {}) {
    return _DateTime.fromFormat(text, fmt, opts);
  }
  /**
   * Create a DateTime from a SQL date, time, or datetime
   * Defaults to en-US if no locale has been specified, regardless of the system's locale
   * @param {string} text - the string to parse
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
   * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
   * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @example DateTime.fromSQL('2017-05-15')
   * @example DateTime.fromSQL('2017-05-15 09:12:34')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
   * @example DateTime.fromSQL('09:12:34.342')
   * @return {DateTime}
   */
  static fromSQL(text, opts = {}) {
    const [vals, parsedZone] = parseSQL(text);
    return parseDataToDateTime(vals, parsedZone, opts, "SQL", text);
  }
  /**
   * Create an invalid DateTime.
   * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent.
   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
   * @return {DateTime}
   */
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidDateTimeError(invalid);
    } else {
      return new _DateTime({ invalid });
    }
  }
  /**
   * Check if an object is an instance of DateTime. Works across context boundaries
   * @param {object} o
   * @return {boolean}
   */
  static isDateTime(o) {
    return o && o.isLuxonDateTime || false;
  }
  /**
   * Produce the format string for a set of options
   * @param formatOpts
   * @param localeOpts
   * @returns {string}
   */
  static parseFormatForOpts(formatOpts, localeOpts = {}) {
    const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));
    return !tokenList ? null : tokenList.map((t) => t ? t.val : null).join("");
  }
  /**
   * Produce the the fully expanded format token for the locale
   * Does NOT quote characters, so quoted tokens will not round trip correctly
   * @param fmt
   * @param localeOpts
   * @returns {string}
   */
  static expandFormat(fmt, localeOpts = {}) {
    const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));
    return expanded.map((t) => t.val).join("");
  }
  static resetCache() {
    zoneOffsetTs = void 0;
    zoneOffsetGuessCache.clear();
  }
  // INFO
  /**
   * Get the value of unit.
   * @param {string} unit - a unit such as 'minute' or 'day'
   * @example DateTime.local(2017, 7, 4).get('month'); //=> 7
   * @example DateTime.local(2017, 7, 4).get('day'); //=> 4
   * @return {number}
   */
  get(unit3) {
    return this[unit3];
  }
  /**
   * Returns whether the DateTime is valid. Invalid DateTimes occur when:
   * * The DateTime was created from invalid calendar information, such as the 13th month or February 30
   * * The DateTime was created by an operation on another invalid date
   * @type {boolean}
   */
  get isValid() {
    return this.invalid === null;
  }
  /**
   * Returns an error code if this DateTime is invalid, or null if the DateTime is valid
   * @type {string}
   */
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  /**
   * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
   * @type {string}
   */
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  /**
   * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
   *
   * @type {string}
   */
  get locale() {
    return this.isValid ? this.loc.locale : null;
  }
  /**
   * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
   *
   * @type {string}
   */
  get numberingSystem() {
    return this.isValid ? this.loc.numberingSystem : null;
  }
  /**
   * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
   *
   * @type {string}
   */
  get outputCalendar() {
    return this.isValid ? this.loc.outputCalendar : null;
  }
  /**
   * Get the time zone associated with this DateTime.
   * @type {Zone}
   */
  get zone() {
    return this._zone;
  }
  /**
   * Get the name of the time zone.
   * @type {string}
   */
  get zoneName() {
    return this.isValid ? this.zone.name : null;
  }
  /**
   * Get the year
   * @example DateTime.local(2017, 5, 25).year //=> 2017
   * @type {number}
   */
  get year() {
    return this.isValid ? this.c.year : NaN;
  }
  /**
   * Get the quarter
   * @example DateTime.local(2017, 5, 25).quarter //=> 2
   * @type {number}
   */
  get quarter() {
    return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
  }
  /**
   * Get the month (1-12).
   * @example DateTime.local(2017, 5, 25).month //=> 5
   * @type {number}
   */
  get month() {
    return this.isValid ? this.c.month : NaN;
  }
  /**
   * Get the day of the month (1-30ish).
   * @example DateTime.local(2017, 5, 25).day //=> 25
   * @type {number}
   */
  get day() {
    return this.isValid ? this.c.day : NaN;
  }
  /**
   * Get the hour of the day (0-23).
   * @example DateTime.local(2017, 5, 25, 9).hour //=> 9
   * @type {number}
   */
  get hour() {
    return this.isValid ? this.c.hour : NaN;
  }
  /**
   * Get the minute of the hour (0-59).
   * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
   * @type {number}
   */
  get minute() {
    return this.isValid ? this.c.minute : NaN;
  }
  /**
   * Get the second of the minute (0-59).
   * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
   * @type {number}
   */
  get second() {
    return this.isValid ? this.c.second : NaN;
  }
  /**
   * Get the millisecond of the second (0-999).
   * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
   * @type {number}
   */
  get millisecond() {
    return this.isValid ? this.c.millisecond : NaN;
  }
  /**
   * Get the week year
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2014, 12, 31).weekYear //=> 2015
   * @type {number}
   */
  get weekYear() {
    return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
  }
  /**
   * Get the week number of the week year (1-52ish).
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2017, 5, 25).weekNumber //=> 21
   * @type {number}
   */
  get weekNumber() {
    return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
  }
  /**
   * Get the day of the week.
   * 1 is Monday and 7 is Sunday
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2014, 11, 31).weekday //=> 4
   * @type {number}
   */
  get weekday() {
    return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
  }
  /**
   * Returns true if this date is on a weekend according to the locale, false otherwise
   * @returns {boolean}
   */
  get isWeekend() {
    return this.isValid && this.loc.getWeekendDays().includes(this.weekday);
  }
  /**
   * Get the day of the week according to the locale.
   * 1 is the first day of the week and 7 is the last day of the week.
   * If the locale assigns Sunday as the first day of the week, then a date which is a Sunday will return 1,
   * @returns {number}
   */
  get localWeekday() {
    return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN;
  }
  /**
   * Get the week number of the week year according to the locale. Different locales assign week numbers differently,
   * because the week can start on different days of the week (see localWeekday) and because a different number of days
   * is required for a week to count as the first week of a year.
   * @returns {number}
   */
  get localWeekNumber() {
    return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN;
  }
  /**
   * Get the week year according to the locale. Different locales assign week numbers (and therefor week years)
   * differently, see localWeekNumber.
   * @returns {number}
   */
  get localWeekYear() {
    return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN;
  }
  /**
   * Get the ordinal (meaning the day of the year)
   * @example DateTime.local(2017, 5, 25).ordinal //=> 145
   * @type {number|DateTime}
   */
  get ordinal() {
    return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
  }
  /**
   * Get the human readable short month name, such as 'Oct'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).monthShort //=> Oct
   * @type {string}
   */
  get monthShort() {
    return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null;
  }
  /**
   * Get the human readable long month name, such as 'October'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).monthLong //=> October
   * @type {string}
   */
  get monthLong() {
    return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null;
  }
  /**
   * Get the human readable short weekday, such as 'Mon'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
   * @type {string}
   */
  get weekdayShort() {
    return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null;
  }
  /**
   * Get the human readable long weekday, such as 'Monday'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
   * @type {string}
   */
  get weekdayLong() {
    return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null;
  }
  /**
   * Get the UTC offset of this DateTime in minutes
   * @example DateTime.now().offset //=> -240
   * @example DateTime.utc().offset //=> 0
   * @type {number}
   */
  get offset() {
    return this.isValid ? +this.o : NaN;
  }
  /**
   * Get the short human name for the zone's current offset, for example "EST" or "EDT".
   * Defaults to the system's locale if no locale has been specified
   * @type {string}
   */
  get offsetNameShort() {
    if (this.isValid) {
      return this.zone.offsetName(this.ts, {
        format: "short",
        locale: this.locale
      });
    } else {
      return null;
    }
  }
  /**
   * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
   * Defaults to the system's locale if no locale has been specified
   * @type {string}
   */
  get offsetNameLong() {
    if (this.isValid) {
      return this.zone.offsetName(this.ts, {
        format: "long",
        locale: this.locale
      });
    } else {
      return null;
    }
  }
  /**
   * Get whether this zone's offset ever changes, as in a DST.
   * @type {boolean}
   */
  get isOffsetFixed() {
    return this.isValid ? this.zone.isUniversal : null;
  }
  /**
   * Get whether the DateTime is in a DST.
   * @type {boolean}
   */
  get isInDST() {
    if (this.isOffsetFixed) {
      return false;
    } else {
      return this.offset > this.set({ month: 1, day: 1 }).offset || this.offset > this.set({ month: 5 }).offset;
    }
  }
  /**
   * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC
   * in this DateTime's zone. During DST changes local time can be ambiguous, for example
   * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`.
   * This method will return both possible DateTimes if this DateTime's local time is ambiguous.
   * @returns {DateTime[]}
   */
  getPossibleOffsets() {
    if (!this.isValid || this.isOffsetFixed) {
      return [this];
    }
    const dayMs = 864e5;
    const minuteMs = 6e4;
    const localTS = objToLocalTS(this.c);
    const oEarlier = this.zone.offset(localTS - dayMs);
    const oLater = this.zone.offset(localTS + dayMs);
    const o1 = this.zone.offset(localTS - oEarlier * minuteMs);
    const o2 = this.zone.offset(localTS - oLater * minuteMs);
    if (o1 === o2) {
      return [this];
    }
    const ts1 = localTS - o1 * minuteMs;
    const ts2 = localTS - o2 * minuteMs;
    const c1 = tsToObj(ts1, o1);
    const c2 = tsToObj(ts2, o2);
    if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) {
      return [clone(this, { ts: ts1 }), clone(this, { ts: ts2 })];
    }
    return [this];
  }
  /**
   * Returns true if this DateTime is in a leap year, false otherwise
   * @example DateTime.local(2016).isInLeapYear //=> true
   * @example DateTime.local(2013).isInLeapYear //=> false
   * @type {boolean}
   */
  get isInLeapYear() {
    return isLeapYear(this.year);
  }
  /**
   * Returns the number of days in this DateTime's month
   * @example DateTime.local(2016, 2).daysInMonth //=> 29
   * @example DateTime.local(2016, 3).daysInMonth //=> 31
   * @type {number}
   */
  get daysInMonth() {
    return daysInMonth(this.year, this.month);
  }
  /**
   * Returns the number of days in this DateTime's year
   * @example DateTime.local(2016).daysInYear //=> 366
   * @example DateTime.local(2013).daysInYear //=> 365
   * @type {number}
   */
  get daysInYear() {
    return this.isValid ? daysInYear(this.year) : NaN;
  }
  /**
   * Returns the number of weeks in this DateTime's year
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2004).weeksInWeekYear //=> 53
   * @example DateTime.local(2013).weeksInWeekYear //=> 52
   * @type {number}
   */
  get weeksInWeekYear() {
    return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
  }
  /**
   * Returns the number of weeks in this DateTime's local week year
   * @example DateTime.local(2020, 6, {locale: 'en-US'}).weeksInLocalWeekYear //=> 52
   * @example DateTime.local(2020, 6, {locale: 'de-DE'}).weeksInLocalWeekYear //=> 53
   * @type {number}
   */
  get weeksInLocalWeekYear() {
    return this.isValid ? weeksInWeekYear(
      this.localWeekYear,
      this.loc.getMinDaysInFirstWeek(),
      this.loc.getStartOfWeek()
    ) : NaN;
  }
  /**
   * Returns the resolved Intl options for this DateTime.
   * This is useful in understanding the behavior of formatting methods
   * @param {Object} opts - the same options as toLocaleString
   * @return {Object}
   */
  resolvedLocaleOptions(opts = {}) {
    const { locale: locale3, numberingSystem, calendar: calendar2 } = Formatter.create(
      this.loc.clone(opts),
      opts
    ).resolvedOptions(this);
    return { locale: locale3, numberingSystem, outputCalendar: calendar2 };
  }
  // TRANSFORM
  /**
   * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
   *
   * Equivalent to {@link DateTime#setZone}('utc')
   * @param {number} [offset=0] - optionally, an offset from UTC in minutes
   * @param {Object} [opts={}] - options to pass to `setZone()`
   * @return {DateTime}
   */
  toUTC(offset2 = 0, opts = {}) {
    return this.setZone(FixedOffsetZone.instance(offset2), opts);
  }
  /**
   * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
   *
   * Equivalent to `setZone('local')`
   * @return {DateTime}
   */
  toLocal() {
    return this.setZone(Settings.defaultZone);
  }
  /**
   * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
   *
   * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.
   * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.
   * @param {Object} opts - options
   * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
   * @return {DateTime}
   */
  setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {
    zone = normalizeZone(zone, Settings.defaultZone);
    if (zone.equals(this.zone)) {
      return this;
    } else if (!zone.isValid) {
      return _DateTime.invalid(unsupportedZone(zone));
    } else {
      let newTS = this.ts;
      if (keepLocalTime || keepCalendarTime) {
        const offsetGuess = zone.offset(this.ts);
        const asObj = this.toObject();
        [newTS] = objToTS(asObj, offsetGuess, zone);
      }
      return clone(this, { ts: newTS, zone });
    }
  }
  /**
   * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
   * @param {Object} properties - the properties to set
   * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
   * @return {DateTime}
   */
  reconfigure({ locale: locale3, numberingSystem, outputCalendar } = {}) {
    const loc = this.loc.clone({ locale: locale3, numberingSystem, outputCalendar });
    return clone(this, { loc });
  }
  /**
   * "Set" the locale. Returns a newly-constructed DateTime.
   * Just a convenient alias for reconfigure({ locale })
   * @example DateTime.local(2017, 5, 25).setLocale('en-GB')
   * @return {DateTime}
   */
  setLocale(locale3) {
    return this.reconfigure({ locale: locale3 });
  }
  /**
   * "Set" the values of specified units. Returns a newly-constructed DateTime.
   * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.
   *
   * This method also supports setting locale-based week units, i.e. `localWeekday`, `localWeekNumber` and `localWeekYear`.
   * They cannot be mixed with ISO-week units like `weekday`.
   * @param {Object} values - a mapping of units to numbers
   * @example dt.set({ year: 2017 })
   * @example dt.set({ hour: 8, minute: 30 })
   * @example dt.set({ weekday: 5 })
   * @example dt.set({ year: 2005, ordinal: 234 })
   * @return {DateTime}
   */
  set(values) {
    if (!this.isValid) return this;
    const normalized = normalizeObject(values, normalizeUnitWithLocalWeeks);
    const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, this.loc);
    const settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber;
    if ((containsGregor || containsOrdinal) && definiteWeekDef) {
      throw new ConflictingSpecificationError(
        "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
      );
    }
    if (containsGregorMD && containsOrdinal) {
      throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
    }
    let mixed;
    if (settingWeekStuff) {
      mixed = weekToGregorian(
        { ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), ...normalized },
        minDaysInFirstWeek,
        startOfWeek
      );
    } else if (!isUndefined(normalized.ordinal)) {
      mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized });
    } else {
      mixed = { ...this.toObject(), ...normalized };
      if (isUndefined(normalized.day)) {
        mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
      }
    }
    const [ts, o] = objToTS(mixed, this.o, this.zone);
    return clone(this, { ts, o });
  }
  /**
   * Add a period of time to this DateTime and return the resulting DateTime
   *
   * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
   * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   * @example DateTime.now().plus(123) //~> in 123 milliseconds
   * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes
   * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow
   * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday
   * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min
   * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min
   * @return {DateTime}
   */
  plus(duration3) {
    if (!this.isValid) return this;
    const dur = Duration.fromDurationLike(duration3);
    return clone(this, adjustTime(this, dur));
  }
  /**
   * Subtract a period of time to this DateTime and return the resulting DateTime
   * See {@link DateTime#plus}
   * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   @return {DateTime}
   */
  minus(duration3) {
    if (!this.isValid) return this;
    const dur = Duration.fromDurationLike(duration3).negate();
    return clone(this, adjustTime(this, dur));
  }
  /**
   * "Set" this DateTime to the beginning of a unit of time.
   * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
   * @param {Object} opts - options
   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week
   * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
   * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
   * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays
   * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
   * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
   * @return {DateTime}
   */
  startOf(unit3, { useLocaleWeeks = false } = {}) {
    if (!this.isValid) return this;
    const o = {}, normalizedUnit = Duration.normalizeUnit(unit3);
    switch (normalizedUnit) {
      case "years":
        o.month = 1;
      // falls through
      case "quarters":
      case "months":
        o.day = 1;
      // falls through
      case "weeks":
      case "days":
        o.hour = 0;
      // falls through
      case "hours":
        o.minute = 0;
      // falls through
      case "minutes":
        o.second = 0;
      // falls through
      case "seconds":
        o.millisecond = 0;
        break;
    }
    if (normalizedUnit === "weeks") {
      if (useLocaleWeeks) {
        const startOfWeek = this.loc.getStartOfWeek();
        const { weekday } = this;
        if (weekday < startOfWeek) {
          o.weekNumber = this.weekNumber - 1;
        }
        o.weekday = startOfWeek;
      } else {
        o.weekday = 1;
      }
    }
    if (normalizedUnit === "quarters") {
      const q = Math.ceil(this.month / 3);
      o.month = (q - 1) * 3 + 1;
    }
    return this.set(o);
  }
  /**
   * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time
   * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
   * @param {Object} opts - options
   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week
   * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
   * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
   * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays
   * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
   * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
   * @return {DateTime}
   */
  endOf(unit3, opts) {
    return this.isValid ? this.plus({ [unit3]: 1 }).startOf(unit3, opts).minus(1) : this;
  }
  // OUTPUT
  /**
   * Returns a string representation of this DateTime formatted according to the specified format string.
   * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).
   * Defaults to en-US if no locale has been specified, regardless of the system's locale.
   * @param {string} fmt - the format string
   * @param {Object} opts - opts to override the configuration options on this DateTime
   * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
   * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
   * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22'
   * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
   * @return {string}
   */
  toFormat(fmt, opts = {}) {
    return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID;
  }
  /**
   * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
   * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation
   * of the DateTime in the assigned locale.
   * Defaults to the system's locale if no locale has been specified
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
   * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options
   * @param {Object} opts - opts to override the configuration options on this DateTime
   * @example DateTime.now().toLocaleString(); //=> 4/20/2017
   * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'
   * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'
   * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022'
   * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'
   * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'
   * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'
   * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'
   * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'
   * @return {string}
   */
  toLocaleString(formatOpts = DATE_SHORT, opts = {}) {
    return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID;
  }
  /**
   * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.
   * Defaults to the system's locale if no locale has been specified
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts
   * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.
   * @example DateTime.now().toLocaleParts(); //=> [
   *                                   //=>   { type: 'day', value: '25' },
   *                                   //=>   { type: 'literal', value: '/' },
   *                                   //=>   { type: 'month', value: '05' },
   *                                   //=>   { type: 'literal', value: '/' },
   *                                   //=>   { type: 'year', value: '1982' }
   *                                   //=> ]
   */
  toLocaleParts(opts = {}) {
    return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : [];
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime
   * @param {Object} opts - options
   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.extendedZone=false] - add the time zone format extension
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @param {string} [opts.precision='milliseconds'] - truncate output to desired presicion: 'years', 'months', 'days', 'hours', 'minutes', 'seconds' or 'milliseconds'. When precision and suppressSeconds or suppressMilliseconds are used together, precision sets the maximum unit shown in the output, however seconds or milliseconds will still be suppressed if they are 0.
   * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'
   * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'
   * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'
   * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'
   * @example DateTime.now().toISO({ precision: 'day' }) //=> '2017-04-22Z'
   * @example DateTime.now().toISO({ precision: 'minute' }) //=> '2017-04-22T20:47Z'
   * @return {string|null}
   */
  toISO({
    format: format2 = "extended",
    suppressSeconds = false,
    suppressMilliseconds = false,
    includeOffset = true,
    extendedZone = false,
    precision = "milliseconds"
  } = {}) {
    if (!this.isValid) {
      return null;
    }
    precision = normalizeUnit(precision);
    const ext = format2 === "extended";
    let c = toISODate(this, ext, precision);
    if (orderedUnits.indexOf(precision) >= 3) c += "T";
    c += toISOTime(
      this,
      ext,
      suppressSeconds,
      suppressMilliseconds,
      includeOffset,
      extendedZone,
      precision
    );
    return c;
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime's date component
   * @param {Object} opts - options
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @param {string} [opts.precision='day'] - truncate output to desired precision: 'years', 'months', or 'days'.
   * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
   * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
   * @example DateTime.utc(1982, 5, 25).toISODate({ precision: 'month' }) //=> '1982-05'
   * @return {string|null}
   */
  toISODate({ format: format2 = "extended", precision = "day" } = {}) {
    if (!this.isValid) {
      return null;
    }
    return toISODate(this, format2 === "extended", normalizeUnit(precision));
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime's week date
   * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'
   * @return {string}
   */
  toISOWeekDate() {
    return toTechFormat(this, "kkkk-'W'WW-c");
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime's time component
   * @param {Object} opts - options
   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.extendedZone=true] - add the time zone format extension
   * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @param {string} [opts.precision='milliseconds'] - truncate output to desired presicion: 'hours', 'minutes', 'seconds' or 'milliseconds'. When precision and suppressSeconds or suppressMilliseconds are used together, precision sets the maximum unit shown in the output, however seconds or milliseconds will still be suppressed if they are 0.
   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'
   * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'
   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'
   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'
   * @example DateTime.utc().set({ hour: 7, minute: 34, second: 56 }).toISOTime({ precision: 'minute' }) //=> '07:34Z'
   * @return {string}
   */
  toISOTime({
    suppressMilliseconds = false,
    suppressSeconds = false,
    includeOffset = true,
    includePrefix = false,
    extendedZone = false,
    format: format2 = "extended",
    precision = "milliseconds"
  } = {}) {
    if (!this.isValid) {
      return null;
    }
    precision = normalizeUnit(precision);
    let c = includePrefix && orderedUnits.indexOf(precision) >= 3 ? "T" : "";
    return c + toISOTime(
      this,
      format2 === "extended",
      suppressSeconds,
      suppressMilliseconds,
      includeOffset,
      extendedZone,
      precision
    );
  }
  /**
   * Returns an RFC 2822-compatible string representation of this DateTime
   * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'
   * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'
   * @return {string}
   */
  toRFC2822() {
    return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.
   * Specifically, the string conforms to RFC 1123.
   * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
   * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'
   * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'
   * @return {string}
   */
  toHTTP() {
    return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in SQL Date
   * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'
   * @return {string|null}
   */
  toSQLDate() {
    if (!this.isValid) {
      return null;
    }
    return toISODate(this, true);
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in SQL Time
   * @param {Object} opts - options
   * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
   * @example DateTime.utc().toSQL() //=> '05:15:16.345'
   * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'
   * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'
   * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'
   * @return {string}
   */
  toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {
    let fmt = "HH:mm:ss.SSS";
    if (includeZone || includeOffset) {
      if (includeOffsetSpace) {
        fmt += " ";
      }
      if (includeZone) {
        fmt += "z";
      } else if (includeOffset) {
        fmt += "ZZ";
      }
    }
    return toTechFormat(this, fmt, true);
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in SQL DateTime
   * @param {Object} opts - options
   * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
   * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'
   * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'
   * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'
   * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'
   * @return {string}
   */
  toSQL(opts = {}) {
    if (!this.isValid) {
      return null;
    }
    return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;
  }
  /**
   * Returns a string representation of this DateTime appropriate for debugging
   * @return {string}
   */
  toString() {
    return this.isValid ? this.toISO() : INVALID;
  }
  /**
   * Returns a string representation of this DateTime appropriate for the REPL.
   * @return {string}
   */
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
    if (this.isValid) {
      return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`;
    } else {
      return `DateTime { Invalid, reason: ${this.invalidReason} }`;
    }
  }
  /**
   * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}
   * @return {number}
   */
  valueOf() {
    return this.toMillis();
  }
  /**
   * Returns the epoch milliseconds of this DateTime.
   * @return {number}
   */
  toMillis() {
    return this.isValid ? this.ts : NaN;
  }
  /**
   * Returns the epoch seconds (including milliseconds in the fractional part) of this DateTime.
   * @return {number}
   */
  toSeconds() {
    return this.isValid ? this.ts / 1e3 : NaN;
  }
  /**
   * Returns the epoch seconds (as a whole number) of this DateTime.
   * @return {number}
   */
  toUnixInteger() {
    return this.isValid ? Math.floor(this.ts / 1e3) : NaN;
  }
  /**
   * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.
   * @return {string}
   */
  toJSON() {
    return this.toISO();
  }
  /**
   * Returns a BSON serializable equivalent to this DateTime.
   * @return {Date}
   */
  toBSON() {
    return this.toJSDate();
  }
  /**
   * Returns a JavaScript object with this DateTime's year, month, day, and so on.
   * @param opts - options for generating the object
   * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
   * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
   * @return {Object}
   */
  toObject(opts = {}) {
    if (!this.isValid) return {};
    const base = { ...this.c };
    if (opts.includeConfig) {
      base.outputCalendar = this.outputCalendar;
      base.numberingSystem = this.loc.numberingSystem;
      base.locale = this.loc.locale;
    }
    return base;
  }
  /**
   * Returns a JavaScript Date equivalent to this DateTime.
   * @return {Date}
   */
  toJSDate() {
    return new Date(this.isValid ? this.ts : NaN);
  }
  // COMPARE
  /**
   * Return the difference between two DateTimes as a Duration.
   * @param {DateTime} otherDateTime - the DateTime to compare this one to
   * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.
   * @param {Object} opts - options that affect the creation of the Duration
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @example
   * var i1 = DateTime.fromISO('1982-05-25T09:45'),
   *     i2 = DateTime.fromISO('1983-10-14T10:30');
   * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }
   * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }
   * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }
   * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }
   * @return {Duration}
   */
  diff(otherDateTime, unit3 = "milliseconds", opts = {}) {
    if (!this.isValid || !otherDateTime.isValid) {
      return Duration.invalid("created by diffing an invalid DateTime");
    }
    const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts };
    const units = maybeArray(unit3).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff(earlier, later, units, durOpts);
    return otherIsLater ? diffed.negate() : diffed;
  }
  /**
   * Return the difference between this DateTime and right now.
   * See {@link DateTime#diff}
   * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration
   * @param {Object} opts - options that affect the creation of the Duration
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @return {Duration}
   */
  diffNow(unit3 = "milliseconds", opts = {}) {
    return this.diff(_DateTime.now(), unit3, opts);
  }
  /**
   * Return an Interval spanning between this DateTime and another DateTime
   * @param {DateTime} otherDateTime - the other end point of the Interval
   * @return {Interval|DateTime}
   */
  until(otherDateTime) {
    return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
  }
  /**
   * Return whether this DateTime is in the same unit of time as another DateTime.
   * Higher-order units must also be identical for this function to return `true`.
   * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.
   * @param {DateTime} otherDateTime - the other DateTime
   * @param {string} unit - the unit of time to check sameness on
   * @param {Object} opts - options
   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; only the locale of this DateTime is used
   * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day
   * @return {boolean}
   */
  hasSame(otherDateTime, unit3, opts) {
    if (!this.isValid) return false;
    const inputMs = otherDateTime.valueOf();
    const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });
    return adjustedToZone.startOf(unit3, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit3, opts);
  }
  /**
   * Equality check
   * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid.
   * To compare just the millisecond values, use `+dt1 === +dt2`.
   * @param {DateTime} other - the other DateTime
   * @return {boolean}
   */
  equals(other) {
    return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc);
  }
  /**
   * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your
   * platform supports Intl.RelativeTimeFormat. Rounds towards zero by default.
   * @param {Object} options - options that affect the output
   * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
   * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
   * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
   * @param {boolean} [options.round=true] - whether to round the numbers in the output.
   * @param {string} [options.rounding="trunc"] - rounding method to use when rounding the numbers in the output. Can be "trunc" (toward zero), "expand" (away from zero), "round", "floor", or "ceil".
   * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
   * @param {string} options.locale - override the locale of this DateTime
   * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
   * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day"
   * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día"
   * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures"
   * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago"
   * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago"
   * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago"
   */
  toRelative(options = {}) {
    if (!this.isValid) return null;
    const base = options.base || _DateTime.fromObject({}, { zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0;
    let units = ["years", "months", "days", "hours", "minutes", "seconds"];
    let unit3 = options.unit;
    if (Array.isArray(options.unit)) {
      units = options.unit;
      unit3 = void 0;
    }
    return diffRelative(base, this.plus(padding), {
      ...options,
      numeric: "always",
      units,
      unit: unit3
    });
  }
  /**
   * Returns a string representation of this date relative to today, such as "yesterday" or "next month".
   * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.
   * @param {Object} options - options that affect the output
   * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
   * @param {string} options.locale - override the locale of this DateTime
   * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days"
   * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
   * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow"
   * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana"
   * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain"
   * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago"
   */
  toRelativeCalendar(options = {}) {
    if (!this.isValid) return null;
    return diffRelative(options.base || _DateTime.fromObject({}, { zone: this.zone }), this, {
      ...options,
      numeric: "auto",
      units: ["years", "months", "days"],
      calendary: true
    });
  }
  /**
   * Return the min of several date times
   * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum
   * @return {DateTime} the min DateTime, or undefined if called with no argument
   */
  static min(...dateTimes) {
    if (!dateTimes.every(_DateTime.isDateTime)) {
      throw new InvalidArgumentError("min requires all arguments be DateTimes");
    }
    return bestBy(dateTimes, (i) => i.valueOf(), Math.min);
  }
  /**
   * Return the max of several date times
   * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum
   * @return {DateTime} the max DateTime, or undefined if called with no argument
   */
  static max(...dateTimes) {
    if (!dateTimes.every(_DateTime.isDateTime)) {
      throw new InvalidArgumentError("max requires all arguments be DateTimes");
    }
    return bestBy(dateTimes, (i) => i.valueOf(), Math.max);
  }
  // MISC
  /**
   * Explain how a string would be parsed by fromFormat()
   * @param {string} text - the string to parse
   * @param {string} fmt - the format the string is expected to be in (see description)
   * @param {Object} options - options taken by fromFormat()
   * @return {Object}
   */
  static fromFormatExplain(text, fmt, options = {}) {
    const { locale: locale3 = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({
      locale: locale3,
      numberingSystem,
      defaultToEN: true
    });
    return explainFromTokens(localeToUse, text, fmt);
  }
  /**
   * @deprecated use fromFormatExplain instead
   */
  static fromStringExplain(text, fmt, options = {}) {
    return _DateTime.fromFormatExplain(text, fmt, options);
  }
  /**
   * Build a parser for `fmt` using the given locale. This parser can be passed
   * to {@link DateTime.fromFormatParser} to a parse a date in this format. This
   * can be used to optimize cases where many dates need to be parsed in a
   * specific format.
   *
   * @param {String} fmt - the format the string is expected to be in (see
   * description)
   * @param {Object} options - options used to set locale and numberingSystem
   * for parser
   * @returns {TokenParser} - opaque object to be used
   */
  static buildFormatParser(fmt, options = {}) {
    const { locale: locale3 = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({
      locale: locale3,
      numberingSystem,
      defaultToEN: true
    });
    return new TokenParser(localeToUse, fmt);
  }
  /**
   * Create a DateTime from an input string and format parser.
   *
   * The format parser must have been created with the same locale as this call.
   *
   * @param {String} text - the string to parse
   * @param {TokenParser} formatParser - parser from {@link DateTime.buildFormatParser}
   * @param {Object} opts - options taken by fromFormat()
   * @returns {DateTime}
   */
  static fromFormatParser(text, formatParser, opts = {}) {
    if (isUndefined(text) || isUndefined(formatParser)) {
      throw new InvalidArgumentError(
        "fromFormatParser requires an input string and a format parser"
      );
    }
    const { locale: locale3 = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({
      locale: locale3,
      numberingSystem,
      defaultToEN: true
    });
    if (!localeToUse.equals(formatParser.locale)) {
      throw new InvalidArgumentError(
        `fromFormatParser called with a locale of ${localeToUse}, but the format parser was created for ${formatParser.locale}`
      );
    }
    const { result, zone, specificOffset, invalidReason } = formatParser.explainFromTokens(text);
    if (invalidReason) {
      return _DateTime.invalid(invalidReason);
    } else {
      return parseDataToDateTime(
        result,
        zone,
        opts,
        `format ${formatParser.format}`,
        text,
        specificOffset
      );
    }
  }
  // FORMAT PRESETS
  /**
   * {@link DateTime#toLocaleString} format like 10/14/1983
   * @type {Object}
   */
  static get DATE_SHORT() {
    return DATE_SHORT;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'
   * @type {Object}
   */
  static get DATE_MED() {
    return DATE_MED;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'
   * @type {Object}
   */
  static get DATE_MED_WITH_WEEKDAY() {
    return DATE_MED_WITH_WEEKDAY;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'October 14, 1983'
   * @type {Object}
   */
  static get DATE_FULL() {
    return DATE_FULL;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'
   * @type {Object}
   */
  static get DATE_HUGE() {
    return DATE_HUGE;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_SIMPLE() {
    return TIME_SIMPLE;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_WITH_SECONDS() {
    return TIME_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_WITH_SHORT_OFFSET() {
    return TIME_WITH_SHORT_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_WITH_LONG_OFFSET() {
    return TIME_WITH_LONG_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_SIMPLE() {
    return TIME_24_SIMPLE;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_WITH_SECONDS() {
    return TIME_24_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_WITH_SHORT_OFFSET() {
    return TIME_24_WITH_SHORT_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_WITH_LONG_OFFSET() {
    return TIME_24_WITH_LONG_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_SHORT() {
    return DATETIME_SHORT;
  }
  /**
   * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_SHORT_WITH_SECONDS() {
    return DATETIME_SHORT_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_MED() {
    return DATETIME_MED;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_MED_WITH_SECONDS() {
    return DATETIME_MED_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_MED_WITH_WEEKDAY() {
    return DATETIME_MED_WITH_WEEKDAY;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_FULL() {
    return DATETIME_FULL;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_FULL_WITH_SECONDS() {
    return DATETIME_FULL_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_HUGE() {
    return DATETIME_HUGE;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_HUGE_WITH_SECONDS() {
    return DATETIME_HUGE_WITH_SECONDS;
  }
};
function friendlyDateTime(dateTimeish) {
  if (DateTime.isDateTime(dateTimeish)) {
    return dateTimeish;
  } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {
    return DateTime.fromJSDate(dateTimeish);
  } else if (dateTimeish && typeof dateTimeish === "object") {
    return DateTime.fromObject(dateTimeish);
  } else {
    throw new InvalidArgumentError(
      `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`
    );
  }
}
var VERSION = "3.7.2";

// src/datalink.mts
var datalink_exports = {};
__export(datalink_exports, {
  ConnectionsResponse: () => ConnectionsResponse,
  DEFAULT_ARCH: () => DEFAULT_ARCH,
  DEFAULT_PROGRAM: () => DEFAULT_PROGRAM,
  DataLinkConnection: () => DataLinkConnection,
  DataLinkIdStats: () => DataLinkIdStats,
  DataLinkPacket: () => DataLinkPacket,
  DataLinkResponse: () => DataLinkResponse,
  DataLinkStats: () => DataLinkStats,
  EARTHSCOPE_RINGSERVER_URL: () => EARTHSCOPE_RINGSERVER_URL,
  ENDSTREAM: () => ENDSTREAM,
  ERROR: () => ERROR,
  ID: () => ID,
  INFO: () => INFO,
  IRIS_RINGSERVER_URL: () => IRIS_RINGSERVER_URL,
  JSON_TYPE: () => JSON_TYPE,
  MAX_PROC_NUM: () => MAX_PROC_NUM,
  MODE: () => MODE,
  MSEED3_TYPE: () => MSEED3_TYPE,
  MSEED_TYPE: () => MSEED_TYPE,
  OK: () => OK,
  PACKET: () => PACKET,
  QUERY_MODE: () => QUERY_MODE,
  STREAM: () => STREAM,
  STREAM_MODE: () => STREAM_MODE,
  StatusResponse: () => StatusResponse,
  StreamStat: () => StreamStat,
  StreamsResponse: () => StreamsResponse,
  ThreadStat: () => ThreadStat,
  USER_BROWSER: () => USER_BROWSER,
  WS_DATALINK_SUBPROTOCOL: () => WS_DATALINK_SUBPROTOCOL,
  daliDateTime: () => daliDateTime,
  dateTimeToHPTime: () => dateTimeToHPTime,
  extractDLProto: () => extractDLProto,
  hpTimeToDateTime: () => hpTimeToDateTime,
  stringToUint8Array: () => stringToUint8Array
});

// src/util.mts
var util_exports = {};
__export(util_exports, {
  BINARY_MIME: () => BINARY_MIME,
  DEBUG_ELEMENT: () => DEBUG_ELEMENT,
  JSONAPI_MIME: () => JSONAPI_MIME,
  JSON_MIME: () => JSON_MIME,
  SVG_MIME: () => SVG_MIME,
  SVG_NS: () => SVG_NS,
  SeisPlotDebugElement: () => SeisPlotDebugElement,
  TEXT_MIME: () => TEXT_MIME,
  UTC_OPTIONS: () => UTC_OPTIONS,
  WAY_FUTURE: () => WAY_FUTURE,
  WAY_PAST: () => WAY_PAST,
  XHTML_NS: () => XHTML_NS,
  XML_MIME: () => XML_MIME,
  anplusb: () => anplusb,
  asStringDictionary: () => asStringDictionary,
  calcClockOffset: () => calcClockOffset,
  centerTimeDuration: () => centerTimeDuration,
  checkLuxonValid: () => checkLuxonValid,
  checkProtocol: () => checkProtocol,
  checkStringOrDate: () => checkStringOrDate,
  cloneFetchInitObj: () => cloneFetchInitObj,
  createSVGElement: () => createSVGElement,
  dataViewToString: () => dataViewToString,
  defaultFetchInitObj: () => defaultFetchInitObj,
  default_fetch: () => default_fetch,
  doBoolGetterSetter: () => doBoolGetterSetter,
  doFetchWithTimeout: () => doFetchWithTimeout,
  doFloatGetterSetter: () => doFloatGetterSetter,
  doIntGetterSetter: () => doIntGetterSetter,
  doMomentGetterSetter: () => doMomentGetterSetter,
  doStringGetterSetter: () => doStringGetterSetter,
  downloadBlobAsFile: () => downloadBlobAsFile,
  durationEnd: () => durationEnd,
  errorFetch: () => errorFetch,
  fixProtocolInUrl: () => fixProtocolInUrl,
  getFetch: () => getFetch,
  hasArgs: () => hasArgs,
  hasNoArgs: () => hasNoArgs,
  isDef: () => isDef,
  isError: () => isError,
  isNonEmptyStringArg: () => isNonEmptyStringArg,
  isNumArg: () => isNumArg,
  isObject: () => isObject,
  isStringArg: () => isStringArg,
  isoToDateTime: () => isoToDateTime,
  log: () => log,
  makeParam: () => makeParam,
  makePostParam: () => makePostParam,
  meanOfSlice: () => meanOfSlice,
  mightBeXml: () => mightBeXml,
  nameForTimeZone: () => nameForTimeZone,
  pullJson: () => pullJson,
  pullText: () => pullText,
  reErrorWithMessage: () => reErrorWithMessage,
  setDefaultFetch: () => setDefaultFetch,
  startDuration: () => startDuration,
  startEnd: () => startEnd,
  stringify: () => stringify,
  toError: () => toError,
  toIsoWoZ: () => toIsoWoZ,
  toJSDate: () => toJSDate,
  updateVersionText: () => updateVersionText,
  validEndTime: () => validEndTime,
  validStartTime: () => validStartTime,
  warn: () => warn
});

// src/version.mts
var version = "3.2.6";

// src/util.mts
var XML_MIME = "application/xml";
var JSON_MIME = "application/json";
var JSONAPI_MIME = "application/vnd.api+json";
var SVG_MIME = "image/svg+xml";
var TEXT_MIME = "text/plain";
var BINARY_MIME = "application/octet-stream";
var UTC_OPTIONS = { zone: FixedOffsetZone.utcInstance };
function hasArgs(value) {
  return arguments.length !== 0 && typeof value !== "undefined";
}
function hasNoArgs(value) {
  return arguments.length === 0 || typeof value === "undefined";
}
function isStringArg(value) {
  return arguments.length !== 0 && (typeof value === "string" || isObject(value) && value instanceof String);
}
function isNumArg(value) {
  return arguments.length !== 0 && (typeof value === "number" || isObject(value) && value instanceof Number);
}
function isNonEmptyStringArg(value) {
  return arguments.length !== 0 && isStringArg(value) && value.length !== 0;
}
function isObject(obj) {
  return obj !== null && typeof obj === "object";
}
function isDef(value) {
  return value !== null && value !== void 0;
}
function reErrorWithMessage(err, message) {
  let out;
  if (!isDef(err)) {
    out = new Error(`${message}`);
  } else if (typeof err === "string") {
    out = new Error(`${message} ${err}`);
  } else if (err instanceof Error) {
    err.message = `${message} ${err.message}`;
    out = err;
  } else {
    out = new Error(`${message} ${stringify(err)}`);
  }
  return out;
}
function asStringDictionary(inobj) {
  if (typeof inobj !== "object") {
    throw new Error(`Expect obj to be object, but was ${stringify(inobj)}`);
  }
  const obj = inobj;
  return obj;
}
function doStringGetterSetter(inobj, field, value) {
  const hiddenField = `_${field}`;
  const obj = asStringDictionary(inobj);
  if (hasNoArgs(value) || value === null) {
    obj[hiddenField] = void 0;
  } else if (isStringArg(value)) {
    obj[hiddenField] = value;
  } else {
    throw new Error(
      `${field} value argument is optional or string, but was type ${typeof value}, '${value}' `
    );
  }
  return inobj;
}
function doBoolGetterSetter(inobj, field, value) {
  const hiddenField = `_${field}`;
  const obj = asStringDictionary(inobj);
  if (hasNoArgs(value) || value === null) {
    obj[hiddenField] = void 0;
  } else if (value === true || value === false) {
    obj[hiddenField] = value;
  } else {
    throw new Error(
      `${field} value argument is optional or boolean, but was type ${typeof value}, '${value}' `
    );
  }
  return inobj;
}
function doIntGetterSetter(inobj, field, value) {
  const hiddenField = `_${field}`;
  const obj = asStringDictionary(inobj);
  if (hasNoArgs(value) || value === null) {
    obj[hiddenField] = void 0;
  } else if (isNumArg(value)) {
    obj[hiddenField] = value;
  } else if (isStringArg(value) && Number.isSafeInteger(Number(value))) {
    obj[hiddenField] = parseInt(value);
  } else {
    throw new Error(
      `${field} value argument is optional or integer, but was type ${typeof value}, '${value}' `
    );
  }
  return inobj;
}
function doFloatGetterSetter(inobj, field, value) {
  const hiddenField = `_${field}`;
  const obj = asStringDictionary(inobj);
  if (hasNoArgs(value) || value === null) {
    obj[hiddenField] = void 0;
  } else if (isNumArg(value)) {
    obj[hiddenField] = value;
  } else if (isStringArg(value) && Number.isFinite(Number(value))) {
    obj[hiddenField] = parseFloat(value);
  } else {
    throw new Error(
      `value argument is optional or number, but was type ${typeof value}, '${value}' `
    );
  }
  return obj;
}
function doMomentGetterSetter(inobj, field, value) {
  const hiddenField = `_${field}`;
  const obj = asStringDictionary(inobj);
  if (hasNoArgs(value) || value === null) {
    obj[hiddenField] = void 0;
  } else if (isDef(value) && isObject(value) && DateTime.isDateTime(value)) {
    obj[hiddenField] = value;
  } else if (isDef(value) && DateTime.isDateTime(checkStringOrDate(value))) {
    obj[hiddenField] = checkStringOrDate(value);
  } else {
    throw new Error(
      `${field} value argument is optional, DateTime, date or date string, but was type ${typeof value}, '${stringify(
        value
      )}' `
    );
  }
  return obj;
}
function dataViewToString(dataView) {
  let out = "";
  for (let i = 0; i < dataView.byteLength; i++) {
    out += String.fromCharCode(dataView.getUint8(i));
  }
  return out;
}
function log(msg) {
  if (console) {
    console.log(`${stringify(msg)}`);
  }
  if (typeof document !== "undefined" && document !== null) {
    const p = document.createElement("p");
    p.textContent = `${stringify(msg)}`;
    const divDebug = document.querySelector("div#debug");
    if (isDef(divDebug)) {
      divDebug.appendChild(p);
    }
  }
}
function isError(error51) {
  return typeof error51 === "object" && error51 !== null && error51 instanceof Error;
}
function toError(maybeError) {
  if (isError(maybeError)) return maybeError;
  try {
    return new Error(JSON.stringify(maybeError));
  } catch {
    return new Error(String(maybeError));
  }
}
var DEBUG_ELEMENT = "sp-debug";
var SeisPlotDebugElement = class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    const shadow = this.shadowRoot;
    if (shadow != null) {
      const pre = shadow.appendChild(document.createElement("pre"));
      pre.appendChild(document.createElement("code"));
    }
  }
  getCodeElement() {
    let code = null;
    const shadow = this.shadowRoot;
    if (shadow != null) {
      code = shadow.querySelector("code");
    }
    return code;
  }
  debug(msg) {
    const code = this.getCodeElement();
    if (code != null) {
      code.textContent = code.textContent + msg.trim() + "\n";
    }
  }
  clear() {
    const code = this.getCodeElement();
    if (code != null) {
      code.innerHTML = "";
    }
  }
};
customElements.define(DEBUG_ELEMENT, SeisPlotDebugElement);
function warn(msg) {
  if (console) {
    console.assert(false, `${stringify(msg)}`);
  }
  if (typeof document !== "undefined" && document !== null) {
    document.querySelectorAll(DEBUG_ELEMENT).forEach((spDebug) => {
      const pre = spDebug.appendChild(document.createElement("pre"));
      const code = pre.appendChild(document.createElement("code"));
      code.textContent = `${stringify(msg)}`;
    });
  }
}
function stringify(value) {
  if (typeof value === "string") {
    return value;
  } else if (typeof value === "number") {
    return value.toString();
  } else if (typeof value === "boolean") {
    return value ? "true" : "false";
  } else if (typeof value === "undefined") {
    return "undefined";
  } else if (typeof value === "function") {
    return "function " + value.name;
  } else if (typeof value === "object") {
    if (value) {
      if (DateTime.isDateTime(value)) {
        const dateTimeValue = value;
        const s2 = dateTimeValue.toISO();
        return dateTimeValue.isValid && s2 ? s2 : `Invalid DateTime: ${dateTimeValue.invalidReason}: ${dateTimeValue.invalidExplanation}`;
      } else {
        return `${value?.constructor?.name} ${JSON.stringify(value)}`;
      }
    } else {
      return `${value}`;
    }
  } else {
    return "<unknown" + typeof value + "???>";
  }
}
function isoToDateTime(val) {
  if (val.toLowerCase() === "now") {
    return DateTime.utc();
  }
  return DateTime.fromISO(val, UTC_OPTIONS);
}
function startEnd(start2, end) {
  if (isStringArg(start2)) {
    start2 = isoToDateTime(start2);
  }
  if (isStringArg(end)) {
    end = isoToDateTime(end);
  }
  return Interval.fromDateTimes(start2, end);
}
function startDuration(start2, duration3) {
  if (isStringArg(start2)) {
    start2 = isoToDateTime(start2);
  }
  if (isStringArg(duration3)) {
    duration3 = Duration.fromISO(duration3);
  } else if (isNumArg(duration3)) {
    duration3 = Duration.fromMillis(1e3 * duration3);
  }
  if (duration3.valueOf() < 0) {
    return Interval.before(start2, duration3.negate());
  } else {
    return Interval.after(start2, duration3);
  }
}
function durationEnd(duration3, end) {
  if (isStringArg(end)) {
    end = isoToDateTime(end);
  }
  if (isStringArg(duration3)) {
    duration3 = Duration.fromISO(duration3);
  } else if (isNumArg(duration3)) {
    duration3 = Duration.fromMillis(1e3 * duration3);
  }
  if (duration3.valueOf() < 0) {
    return Interval.after(end, duration3.negate());
  } else {
    return Interval.before(end, duration3);
  }
}
function centerTimeDuration(center2, duration3) {
  if (isStringArg(center2)) {
    center2 = isoToDateTime(center2);
  }
  if (isStringArg(duration3)) {
    duration3 = Duration.fromISO(duration3);
  } else if (isNumArg(duration3)) {
    duration3 = Duration.fromMillis(1e3 * duration3);
  }
  if (duration3.valueOf() < 0) {
    duration3 = duration3.negate();
  }
  return Interval.fromDateTimes(center2.minus(duration3), center2.plus(duration3));
}
function calcClockOffset(serverTimeUTC) {
  return DateTime.utc().diff(serverTimeUTC).toMillis() * 1e3;
}
var WAY_FUTURE = DateTime.fromISO("2500-01-01T00:00:00Z");
var WAY_PAST = DateTime.fromISO("1900-01-01T00:00:00Z");
function checkStringOrDate(d) {
  if (DateTime.isDateTime(d)) {
    return d;
  } else if (d instanceof Date) {
    return DateTime.fromJSDate(d, UTC_OPTIONS);
  } else if (isNumArg(d)) {
    return DateTime.fromMillis(d, UTC_OPTIONS);
  } else if (isNonEmptyStringArg(d)) {
    const lc = d.toLowerCase();
    if (d.length === 0 || lc === "now") {
      return DateTime.utc();
    } else {
      return isoToDateTime(d);
    }
  }
  throw new Error(`unknown date type: ${stringify(d)} ${typeof d}`);
}
function makeParam(name, val) {
  return `${name}=${encodeURIComponent(stringify(val))}&`;
}
function makePostParam(name, val) {
  return name + "=" + stringify(val) + "\n";
}
function toIsoWoZ(date6) {
  if (date6.isValid) {
    let out = date6.toISO();
    if (out == null) {
      throw new Error(`Bad date: ${stringify(date6)}`);
    }
    if (out.endsWith("Z")) {
      out = out.substring(0, out.length - 1);
    }
    return out;
  } else {
    throw new Error(`${date6.invalidReason}: ${date6.invalidExplanation}`);
  }
}
function validStartTime(interval2) {
  const d = interval2.start;
  if (d == null) {
    throw new Error(`Bad interval: ${stringify(interval2)}`);
  }
  return d;
}
function validEndTime(interval2) {
  const d = interval2.end;
  if (d == null) {
    throw new Error(`Bad interval: ${stringify(interval2)}`);
  }
  return d;
}
function toJSDate(d) {
  if (!d) {
    throw new Error(`Null/undef DateTime: ${d}`);
  }
  if (!d.isValid) {
    throw new Error(`${d.invalidReason}: ${d.invalidExplanation}`);
  }
  return d.toJSDate();
}
function checkLuxonValid(d, msg) {
  if (d == null) {
    const m = msg ? msg : "";
    throw new Error(`Null luxon value: ${d} ${m}`);
  }
  if (!d.isValid) {
    const m = msg ? msg : "";
    throw new Error(
      `Invalid Luxon: ${typeof d} ${d?.constructor?.name} ${d.invalidReason}: ${d.invalidExplanation} ${m}`
    );
  }
  return d;
}
function nameForTimeZone(zone, atTime) {
  if (zone == null || zone instanceof Zone && FixedOffsetZone.utcInstance.equals(zone)) {
    return "UTC";
  } else if (typeof zone === "string") {
    return zone;
  } else if (zone instanceof Zone) {
    if (atTime != null) {
      const ofName = zone.offsetName(atTime.toMillis(), { format: "short" });
      return ofName != null ? ofName : zone.name;
    }
    return zone.name;
  }
  return "unknown";
}
function pullText(url2, timeoutSec2) {
  if (!timeoutSec2) {
    timeoutSec2 = 30;
  }
  const fetchInit = defaultFetchInitObj(TEXT_MIME);
  return doFetchWithTimeout(url2, fetchInit, timeoutSec2 * 1e3).then(
    (response) => {
      if (response.status === 200) {
        return response.text();
      } else {
        throw new Error(`Status not 200: ${response.status}`);
      }
    }
  );
}
function pullJson(url2, timeoutSec2) {
  if (!timeoutSec2) {
    timeoutSec2 = 30;
  }
  const fetchInit = defaultFetchInitObj(JSON_MIME);
  return doFetchWithTimeout(url2, fetchInit, timeoutSec2 * 1e3).then(
    (response) => {
      if (response.status === 200) {
        return response.json();
      } else {
        throw new Error(`Status not 200: ${response.status}`);
      }
    }
  );
}
function checkProtocol(defaultProtocol = "http:") {
  let _protocol = "http:";
  if (defaultProtocol.startsWith("https")) {
    _protocol = "https:";
  }
  if (typeof document !== "undefined" && document !== null && "location" in document && "protocol" in document.location && "https:" === document.location.protocol) {
    _protocol = "https:";
  }
  return _protocol;
}
function fixProtocolInUrl(url2) {
  const protocol = checkProtocol();
  if (url2.startsWith("http:") && protocol === "https:") {
    return `${protocol}${url2.substring(5)}`;
  }
  return url2;
}
function defaultFetchInitObj(mimeType) {
  const headers = {};
  if (isStringArg(mimeType)) {
    headers.Accept = mimeType;
  }
  return {
    cache: "no-cache",
    redirect: "follow",
    mode: "cors",
    referrer: "seisplotjs",
    headers
  };
}
function cloneFetchInitObj(fetchInit) {
  const out = {};
  if (fetchInit) {
    for (const [key, value] of Object.entries(fetchInit)) {
      if (Array.isArray(value)) {
        out[key] = value.slice();
      } else {
        out[key] = value;
      }
    }
  }
  return out;
}
function errorFetch(_url2, _init) {
  throw new Error("There is no fetch!?!?!");
}
var default_fetch = null;
function setDefaultFetch(fetcher) {
  if (fetcher != null) {
    default_fetch = fetcher;
  }
}
function getFetch() {
  if (default_fetch != null) {
    return default_fetch;
  } else if (window != null) {
    return window.fetch;
  } else if (global != null) {
    return global.fetch;
  } else {
    return errorFetch;
  }
}
function doFetchWithTimeout(url2, fetchInit, timeoutSec2, fetcher) {
  const controller = new AbortController();
  const signal = controller.signal;
  if (!fetcher) {
    fetcher = getFetch();
  }
  if (!fetcher) {
    fetcher = window.fetch;
  }
  let internalFetchInit = isDef(fetchInit) ? fetchInit : defaultFetchInitObj();
  internalFetchInit = cloneFetchInitObj(internalFetchInit);
  if (internalFetchInit.redirect === "follow" && internalFetchInit.method === "POST") {
    internalFetchInit.redirect = "manual";
  }
  if (!isDef(timeoutSec2)) {
    timeoutSec2 = 30;
  }
  setTimeout(() => controller.abort(), timeoutSec2 * 1e3);
  internalFetchInit.signal = signal;
  let absoluteUrl;
  if (url2 instanceof URL) {
    absoluteUrl = url2;
  } else if (isStringArg(url2)) {
    if (url2.startsWith("http://") || url2.startsWith("https://")) {
      absoluteUrl = new URL(url2);
    } else {
      absoluteUrl = new URL(url2, document.URL);
    }
  } else {
    throw new Error(`url must be string or URL, ${stringify(url2)}`);
  }
  absoluteUrl.protocol = checkProtocol(absoluteUrl.protocol);
  log(
    `attempt to fetch ${internalFetchInit.method ? internalFetchInit.method : ""} ${stringify(
      absoluteUrl
    )}`
  );
  const fetchForRedirect = fetcher;
  return fetcher(absoluteUrl.href, internalFetchInit).catch((err) => {
    log("fetch failed, possible CORS or PrivacyBadger or NoScript?");
    throw err;
  }).then(function(response) {
    if (response.ok || response.status === 404) {
      return response;
    } else if (response.status >= 300 && response.status <= 399) {
      if (checkProtocol() === "http:" && absoluteUrl.href.startsWith("http://")) {
        const httpsUrl = new URL(`https://${absoluteUrl.href.slice(7)}`);
        const method = internalFetchInit.method ? internalFetchInit.method : "";
        log(
          `attempt fetch redirect ${response.status} ${method} to ${stringify(httpsUrl)}`
        );
        return fetchForRedirect(httpsUrl.href, internalFetchInit).then(
          (httpsResponse) => {
            if (httpsResponse.ok || httpsResponse.status === 404) {
              return httpsResponse;
            } else {
              return httpsResponse.text().then((text) => {
                throw new Error(
                  `fetch response was redirect for http and failed for https. ${response.ok} ${response.status}, ${httpsResponse.ok} ${httpsResponse.status} 
${text}`
                );
              });
            }
          }
        );
      }
    }
    return response.text().then((text) => {
      throw new Error(
        `fetch response was not ok. ${response.ok} ${response.status}
${text}`
      );
    });
  });
}
function downloadBlobAsFile(data, filename, mimeType = "application/octet-stream") {
  if (!data) {
    throw new Error("data is empty");
  }
  if (!filename) filename = "filetodownload.txt";
  const blob = new Blob([data.buffer], { type: mimeType });
  const e = document.createEvent("MouseEvents");
  const a = document.createElement("a");
  a.download = filename;
  a.href = window.URL.createObjectURL(blob);
  a.dataset.downloadurl = [mimeType, a.download, a.href].join(":");
  e.initMouseEvent(
    "click",
    true,
    false,
    window,
    0,
    0,
    0,
    0,
    0,
    false,
    false,
    false,
    false,
    0,
    null
  );
  a.dispatchEvent(e);
}
function meanOfSlice(dataSlice, totalPts) {
  if (dataSlice.length < 8) {
    return (
      // @ts-expect-error different array types confuses typescript
      dataSlice.reduce(function(acc, val) {
        return acc + val;
      }, 0) / totalPts
    );
  } else {
    const byTwo = Math.floor(dataSlice.length / 2);
    return meanOfSlice(dataSlice.slice(0, byTwo), totalPts) + meanOfSlice(dataSlice.slice(byTwo, dataSlice.length), totalPts);
  }
}
var SVG_NS = "http://www.w3.org/2000/svg";
var XHTML_NS = "http://www.w3.org/1999/xhtml";
function createSVGElement(name) {
  return document.createElementNS(SVG_NS, name);
}
function mightBeXml(buf) {
  const initialChars = dataViewToString(new DataView(buf.slice(0, 100))).trimStart();
  if (!initialChars.startsWith("<?xml ")) {
    return false;
  }
  return true;
}
function updateVersionText(selector = ".sp_version") {
  document.querySelectorAll(selector).forEach((el) => {
    el.textContent = version;
  });
}
function anplusb(value) {
  let a = 1;
  let b = 0;
  if (typeof value === "number" && Number.isSafeInteger(value)) {
    a = value;
  } else if (typeof value === "string") {
    const re2 = /^(\d*)n(?:([+-]\d+))?$/;
    const m = re2.exec(value.replaceAll(/\s/g, ""));
    if (m === null) {
      throw new Error(`Unable to parse as 'an+b' (ex. '3n+1'), got: '${value}'`);
    }
    a = m[1] ? +m[1] : a;
    const parsedB = m[2] ? +m[2] : b;
    b = parsedB < 0 ? parsedB + a : parsedB;
  }
  return [a, b];
}

// src/miniseed.mts
var miniseed_exports = {};
__export(miniseed_exports, {
  BTime: () => BTime,
  Blockette: () => Blockette,
  Blockette100: () => Blockette100,
  Blockette1000: () => Blockette1000,
  Blockette1001: () => Blockette1001,
  D_TYPECODE: () => D_TYPECODE,
  DataHeader: () => DataHeader,
  DataRecord: () => DataRecord,
  MINISEED_MIME: () => MINISEED_MIME,
  M_TYPECODE: () => M_TYPECODE,
  Q_TYPECODE: () => Q_TYPECODE,
  R_TYPECODE: () => R_TYPECODE,
  areContiguous: () => areContiguous,
  byChannel: () => byChannel,
  checkByteSwap: () => checkByteSwap,
  createSeismogramSegment: () => createSeismogramSegment,
  merge: () => merge,
  mergeSegments: () => mergeSegments,
  parseBTime: () => parseBTime,
  parseBlockette: () => parseBlockette,
  parseDataRecords: () => parseDataRecords,
  parseSingleDataRecord: () => parseSingleDataRecord,
  parseSingleDataRecordHeader: () => parseSingleDataRecordHeader,
  seismogramPerChannel: () => seismogramPerChannel,
  seismogramSegmentPerChannel: () => seismogramSegmentPerChannel
});

// src/fdsnsourceid.mts
var fdsnsourceid_exports = {};
__export(fdsnsourceid_exports, {
  EMPTY_LOC_CODE: () => EMPTY_LOC_CODE,
  FDSNSourceId: () => FDSNSourceId,
  FDSN_PREFIX: () => FDSN_PREFIX,
  LocationSourceId: () => LocationSourceId,
  NetworkSourceId: () => NetworkSourceId,
  NslcId: () => NslcId,
  SEP: () => SEP,
  SourceIdSorter: () => SourceIdSorter,
  StationSourceId: () => StationSourceId,
  TESTING_NETWORK: () => TESTING_NETWORK,
  TESTING_STATION: () => TESTING_STATION,
  bandCodeForRate: () => bandCodeForRate,
  parseSourceId: () => parseSourceId
});
var FDSN_PREFIX = "FDSN:";
var SEP = "_";
var TESTING_NETWORK = "XX";
var TESTING_STATION = "ABC";
var FDSNSourceId = class _FDSNSourceId {
  constructor(networkCode, stationCode, locationCode, bandCode, sourceCode, subsourceCode) {
    this.networkCode = networkCode;
    this.stationCode = stationCode;
    this.locationCode = locationCode;
    this.bandCode = bandCode;
    this.sourceCode = sourceCode;
    this.subsourceCode = subsourceCode;
  }
  static createUnknown(sampRate, source, subsource) {
    const s2 = source ? source : "Y";
    const ss = subsource ? subsource : "X";
    return new _FDSNSourceId(TESTING_NETWORK, TESTING_STATION, "", bandCodeForRate(sampRate), s2, ss);
  }
  static parse(id2) {
    if (!id2.startsWith(FDSN_PREFIX)) {
      throw new Error(`sourceid must start with ${FDSN_PREFIX}: ${id2}`);
    }
    const items = id2.slice(FDSN_PREFIX.length).split(SEP);
    if (items.length === 6) {
      return new _FDSNSourceId(
        items[0],
        items[1],
        items[2],
        items[3],
        items[4],
        items[5]
      );
    } else {
      throw new Error(
        `FDSN sourceid must have 6 items for channel; separated by '${SEP}': ${id2}`
      );
    }
  }
  static fromNslc(net, sta, loc, channelCode) {
    let band;
    let source;
    let subsource;
    if (channelCode.length === 3) {
      band = channelCode.charAt(0);
      source = channelCode.charAt(1);
      subsource = channelCode.charAt(2);
    } else {
      const b_s_ss = /(\w)_(\w+)_(\w+)/;
      const match2 = b_s_ss.exec(channelCode);
      if (match2) {
        band = match2[1];
        source = match2[2];
        subsource = match2[3];
      } else {
        throw new Error(
          `channel code must be length 3 or have 3 items separated by '${SEP}': ${channelCode}`
        );
      }
    }
    return new _FDSNSourceId(net, sta, loc, band, source, subsource);
  }
  static fromNslcId(nslcId) {
    return _FDSNSourceId.fromNslc(
      nslcId.networkCode,
      nslcId.stationCode,
      nslcId.locationCode,
      nslcId.channelCode
    );
  }
  static parseNslc(nslc, sep = ".") {
    const items = nslc.split(sep);
    if (items.length < 4) {
      throw new Error(
        `channel nslc must have 4 items separated by '${sep}': ${nslc}`
      );
    }
    return _FDSNSourceId.fromNslc(items[0], items[1], items[2], items[3]);
  }
  stationSourceId() {
    return new StationSourceId(this.networkCode, this.stationCode);
  }
  networkSourceId() {
    return new NetworkSourceId(this.networkCode);
  }
  asNslc() {
    let chanCode;
    if (this.bandCode.length === 1 && this.sourceCode.length === 1 && this.subsourceCode.length === 1) {
      chanCode = `${this.bandCode}${this.sourceCode}${this.subsourceCode}`;
    } else {
      chanCode = `${this.bandCode}${SEP}${this.sourceCode}${SEP}${this.subsourceCode}`;
    }
    return new NslcId(
      this.networkCode,
      this.stationCode,
      this.locationCode,
      chanCode
    );
  }
  /**
   * returns a channel code. If this is an old style NSLC, it will be 3 chars,
   * but if either source or subsouce is more than one char, it will be
   * three fields delimited by underscores.
   *
   * @returns the channel code part of the id
   */
  formChannelCode() {
    return this.asNslc().channelCode;
  }
  toString() {
    return `${FDSN_PREFIX}${this.toStringNoPrefix()}`;
  }
  toStringNoPrefix() {
    return `${this.networkCode}${SEP}${this.stationCode}${SEP}${this.locationCode}${SEP}${this.bandCode}${SEP}${this.sourceCode}${SEP}${this.subsourceCode}`;
  }
  equals(other) {
    if (!other) {
      return false;
    }
    return this.toString() === other.toString();
  }
  clone() {
    return new _FDSNSourceId(
      this.networkCode,
      this.stationCode,
      this.locationCode,
      this.bandCode,
      this.sourceCode,
      this.subsourceCode
    );
  }
};
var NetworkSourceId = class _NetworkSourceId {
  constructor(networkCode) {
    this.networkCode = networkCode;
  }
  static parse(id2) {
    if (!id2.startsWith(FDSN_PREFIX)) {
      throw new Error(`sourceid must start with ${FDSN_PREFIX}: ${id2}`);
    }
    const items = id2.slice(FDSN_PREFIX.length).split(SEP);
    if (items.length === 1) {
      return new _NetworkSourceId(items[0]);
    } else {
      throw new Error(
        `FDSN network sourceid must have 1 items; separated by '${SEP}': ${id2}`
      );
    }
    return new _NetworkSourceId(items[0]);
  }
  toString() {
    return `${FDSN_PREFIX}${this.toStringNoPrefix()}`;
  }
  toStringNoPrefix() {
    return this.networkCode;
  }
  equals(other) {
    return this.toString() === other.toString();
  }
};
var StationSourceId = class _StationSourceId {
  constructor(networkCode, stationCode) {
    this.networkCode = networkCode;
    this.stationCode = stationCode;
  }
  static parse(id2) {
    if (!id2.startsWith(FDSN_PREFIX)) {
      throw new Error(`station sourceid must start with ${FDSN_PREFIX}: ${id2}`);
    }
    const items = id2.slice(FDSN_PREFIX.length).split(SEP);
    if (items.length === 2) {
      return new _StationSourceId(items[0], items[1]);
    } else {
      throw new Error(
        `FDSN station sourceid must have 2 items; separated by '${SEP}': ${id2}`
      );
    }
    return new _StationSourceId(items[0], items[1]);
  }
  toString() {
    return `${FDSN_PREFIX}${this.toStringNoPrefix()}`;
  }
  toStringNoPrefix() {
    return `${this.networkCode}${SEP}${this.stationCode}`;
  }
  networkSourceId() {
    return new NetworkSourceId(this.networkCode);
  }
  equals(other) {
    return this.toString() === other.toString();
  }
};
var LocationSourceId = class {
  constructor(networkCode, stationCode, locationCode) {
    this.networkCode = networkCode;
    this.stationCode = stationCode;
    this.locationCode = locationCode;
  }
  toString() {
    return `${FDSN_PREFIX}${this.networkCode}${SEP}${this.stationCode}${SEP}${this.locationCode}`;
  }
  equals(other) {
    return this.toString() === other.toString();
  }
};
function bandCodeForRate(sampRate, resp_lb) {
  if (!sampRate) {
    return "I";
  }
  if (sampRate >= 5e3) {
    return "J";
  } else if (sampRate >= 1e3 && sampRate < 5e3) {
    if (resp_lb && resp_lb < 0.1) {
      return "F";
    }
    return "G";
  } else if (sampRate >= 250 && sampRate < 1e3) {
    if (resp_lb && resp_lb < 0.1) {
      return "C";
    }
    return "D";
  } else if (sampRate >= 80 && sampRate < 250) {
    if (resp_lb && resp_lb < 0.1) {
      return "H";
    }
    return "E";
  } else if (sampRate >= 10 && sampRate < 80) {
    if (resp_lb && resp_lb < 0.1) {
      return "B";
    }
    return "S";
  } else if (sampRate > 1.05 && sampRate < 10) {
    return "M";
  } else if (sampRate >= 0.95 && sampRate <= 1.05) {
    return "L";
  } else if (sampRate >= 0.1 && sampRate < 1) {
    return "V";
  } else if (sampRate >= 0.01 && sampRate < 0.1) {
    return "U";
  } else if (sampRate >= 1e-3 && sampRate < 0.01) {
    return "W";
  } else if (sampRate >= 1e-4 && sampRate < 1e-3) {
    return "R";
  } else if (sampRate >= 1e-5 && sampRate < 1e-4) {
    return "P";
  } else if (sampRate >= 1e-6 && sampRate < 1e-5) {
    return "T";
  } else if (sampRate < 1e-6) {
    return "Q";
  } else {
    throw new Error(`Unable to calc band code for: ${sampRate} ${resp_lb}`);
  }
}
var EMPTY_LOC_CODE = "--";
var NslcId = class _NslcId {
  constructor(net, sta, loc, chan) {
    this.networkCode = net;
    this.stationCode = sta;
    this.locationCode = loc;
    this.channelCode = chan;
  }
  /**
   * Parse NSLC string like CO.JSC.00.HHZ into parts.
   * @param  nslc     string to parse
   * @param  sep="."  seperator, default is '.'
   * @returns NslcId by splitting the string.
   */
  static parse(nslc, sep = ".") {
    const items = nslc.split(sep);
    if (items.length !== 4) {
      throw new Error(
        `NSLC id must have 4 items but was ${items.length}; separated by '${sep}': ${nslc}`
      );
    }
    return new _NslcId(items[0], items[1], items[2], items[3]);
  }
  toString() {
    return `${this.networkCode}_${this.stationCode}_${this.locationCode}_${this.channelCode}`;
  }
  equals(other) {
    if (this.networkCode !== other.networkCode) {
      return false;
    }
    if (this.stationCode !== other.stationCode) {
      return false;
    }
    const myLoc = this.locationCode === EMPTY_LOC_CODE ? "" : this.locationCode;
    const otherLoc = other.locationCode === EMPTY_LOC_CODE ? "" : other.locationCode;
    if (myLoc !== otherLoc) {
      return false;
    }
    if (this.channelCode !== other.channelCode) {
      return false;
    }
    return true;
  }
};
function parseSourceId(id2) {
  if (!id2.startsWith(FDSN_PREFIX)) {
    throw new Error(`sourceid must start with ${FDSN_PREFIX}: ${id2}`);
  }
  const items = id2.slice(FDSN_PREFIX.length).split(SEP);
  if (items.length === 1) {
    return new NetworkSourceId(items[0]);
  } else if (items.length === 2) {
    return new StationSourceId(items[0], items[1]);
  } else if (items.length !== 6) {
    throw new Error(
      `FDSN sourceid must have 6 items for channel, 2 for station or 1 for network; separated by '${SEP}': ${id2}`
    );
  }
  return new FDSNSourceId(
    items[0],
    items[1],
    items[2],
    items[3],
    items[4],
    items[5]
  );
}
function SourceIdSorter(aSid, bSid) {
  if (aSid.networkCode !== bSid.networkCode) {
    return aSid.networkCode.localeCompare(bSid.networkCode);
  }
  if (aSid.stationCode !== bSid.stationCode) {
    return aSid.stationCode.localeCompare(bSid.stationCode);
  }
  if (aSid.locationCode !== bSid.locationCode) {
    return aSid.locationCode.localeCompare(bSid.locationCode);
  }
  if (aSid.bandCode !== bSid.bandCode) {
    return aSid.bandCode.localeCompare(bSid.bandCode);
  }
  if (aSid.sourceCode !== bSid.sourceCode) {
    return aSid.sourceCode.localeCompare(bSid.sourceCode);
  }
  return aSid.subsourceCode.localeCompare(bSid.subsourceCode);
}

// src/seismogramsegment.mts
var seismogramsegment_exports = {};
__export(seismogramsegment_exports, {
  COUNT_UNIT: () => COUNT_UNIT,
  SeismogramSegment: () => SeismogramSegment
});

// src/scale.mts
var scale_exports = {};
__export(scale_exports, {
  AMPLITUDE_MODE: () => AMPLITUDE_MODE,
  AlignmentLinkedTimeScale: () => AlignmentLinkedTimeScale,
  AmplitudeScalable: () => AmplitudeScalable,
  FixedHalfWidthAmplitudeScale: () => FixedHalfWidthAmplitudeScale,
  IndividualAmplitudeScale: () => IndividualAmplitudeScale,
  LinkedAmplitudeScale: () => LinkedAmplitudeScale,
  LinkedTimeScale: () => LinkedTimeScale,
  MinMaxable: () => MinMaxable,
  PHI: () => PHI,
  PanZoomer: () => PanZoomer,
  SQRT_PHI: () => SQRT_PHI,
  TimeScalable: () => TimeScalable
});

// src/transition.mts
var transition_exports = {};
__export(transition_exports, {
  transition: () => transition
});
function transition(drawFn, duration_millis) {
  let startTimestamp = null;
  const transFn = (timestamp) => {
    if (startTimestamp == null) {
      startTimestamp = timestamp;
    }
    const timeOffset = timestamp - startTimestamp;
    if (timeOffset < duration_millis) {
      drawFn(timeOffset / duration_millis);
      window.requestAnimationFrame(transFn);
    } else {
      drawFn(1);
    }
  };
  window.requestAnimationFrame(transFn);
}

// src/scale.mts
var AMPLITUDE_MODE = /* @__PURE__ */ ((AMPLITUDE_MODE2) => {
  AMPLITUDE_MODE2["Raw"] = "raw";
  AMPLITUDE_MODE2["Zero"] = "zero";
  AMPLITUDE_MODE2["MinMax"] = "minmax";
  AMPLITUDE_MODE2["Mean"] = "mean";
  return AMPLITUDE_MODE2;
})(AMPLITUDE_MODE || {});
var _lastId = 0;
var PHI = (1 + Math.sqrt(5)) / 2;
var SQRT_PHI = Math.sqrt(PHI);
var MinMaxable = class _MinMaxable {
  constructor(min, max) {
    this.min = min;
    this.max = max;
  }
  get middle() {
    return (this.min + this.max) / 2;
  }
  get halfWidth() {
    return this.fullWidth / 2;
  }
  get fullWidth() {
    return this.max - this.min;
  }
  union(omm) {
    if (omm) {
      return new _MinMaxable(
        Math.min(this.min, omm.min),
        Math.max(this.max, omm.max)
      );
    } else {
      return this;
    }
  }
  expandPercentage(percent) {
    return _MinMaxable.fromMiddleHalfWidth(
      this.middle,
      this.halfWidth * percent
    );
  }
  /**
   * This as a d3 style 2 element array.
   *
   * @returns length 2 array of min then max
   */
  asArray() {
    return [this.min, this.max];
  }
  toString() {
    return `${this.min} to ${this.max}, mid: ${this.middle} hw: ${this.halfWidth}`;
  }
  /**
   * Create MinMaxable from a d3 style two element array.
   *
   * @param  minmax  array of min then max
   * @returns       new MinMaxable
   */
  static fromArray(minmax) {
    if (minmax.length < 2) {
      throw new Error(`array must have lenght 2, ${minmax.length}`);
    }
    return new _MinMaxable(minmax[0], minmax[1]);
  }
  static fromMiddleHalfWidth(mid, halfWidth) {
    return new _MinMaxable(mid - halfWidth, mid + halfWidth);
  }
};
var AmplitudeScalable = class {
  constructor(minMax) {
    if (minMax) {
      this.minMax = minMax;
    } else {
      this.minMax = new MinMaxable(0, 0);
    }
  }
  notifyAmplitudeChange(_middle, _halfWidth) {
  }
  get middle() {
    return this.minMax.middle;
  }
  get halfWidth() {
    return this.minMax.halfWidth;
  }
  get fullWidth() {
    return this.minMax.fullWidth;
  }
  get min() {
    return this.minMax.min;
  }
  get max() {
    return this.minMax.max;
  }
  toString() {
    return this.minMax.toString();
  }
};
var TimeScalable = class {
  constructor(alignmentTimeOffset, duration3) {
    this.alignmentTimeOffset = alignmentTimeOffset;
    this.duration = duration3;
  }
  notifyTimeRangeChange(_alignmentTimeOffset, _duration) {
  }
};
var LinkedAmplitudeScale = class {
  constructor(graphList) {
    this._scaleId = ++_lastId;
    const glist = graphList ? graphList : [];
    this._halfWidth = 0;
    this._graphSet = new Set(glist);
    this._recalcTimeoutID = null;
  }
  get halfWidth() {
    return this._halfWidth;
  }
  set halfWidth(val) {
    if (this._halfWidth !== val) {
      this._halfWidth = val;
      this.notifyAll().catch((m) => {
        warn(`problem recalc halfWidth: ${m}`);
      });
    }
  }
  /**
   * Links new Seismograph with this amplitude scale.
   *
   * @param   graphList Array of AmplitudeScalable to link
   */
  linkAll(graphList) {
    graphList.forEach((graph) => {
      if ("notifyAmplitudeChange" in graph) {
        this._graphSet.add(graph);
      } else if ("amp_scalable" in graph) {
        this._graphSet.add(graph.amp_scalable);
      } else {
      }
    });
    this.recalculate().catch((m) => {
      warn(`problem recalc linkAll: ${m}`);
    });
  }
  /**
   * Link new Seismograph with this amplitude scale.
   *
   * @param   graph AmplitudeScalable to link
   */
  link(graph) {
    this.linkAll([graph]);
  }
  /**
   * Unlink Seismograph with this amplitude scale.
   *
   * @param   graph AmplitudeScalable to unlink
   */
  unlink(graph) {
    this._graphSet.delete(graph);
    this.recalculate().catch((m) => {
      warn(`problem recalc unlink: ${m}`);
    });
  }
  /**
   * Recalculate the best amplitude scale for all Seismographs. Causes a redraw.
   *
   * @returns array of promise of best amp scales
   */
  recalculate() {
    const maxHalfRange = this.graphList.reduce((acc, cur) => {
      return acc > cur.halfWidth ? acc : cur.halfWidth;
    }, 0);
    let promiseOut;
    if (this.halfWidth !== maxHalfRange) {
      this.halfWidth = maxHalfRange;
      promiseOut = this._internalNotifyAll();
    } else {
      promiseOut = Promise.all(this.graphList.map((g) => Promise.resolve(g)));
    }
    return promiseOut;
  }
  _internalNotifyAll() {
    const hw = this.halfWidth;
    return Promise.all(
      this.graphList.map((g) => {
        return new Promise((resolve) => {
          setTimeout(() => {
            g.notifyAmplitudeChange(g.middle, hw);
            resolve(g);
          }, 10);
        });
      })
    );
  }
  notifyAll() {
    return this._internalNotifyAll();
  }
  get graphList() {
    return Array.from(this._graphSet.values());
  }
};
var IndividualAmplitudeScale = class extends LinkedAmplitudeScale {
  constructor(graphList) {
    super(graphList);
  }
  recalculate() {
    return this.notifyAll();
  }
  notifyAll() {
    return Promise.all(
      this.graphList.map((g) => {
        return new Promise((resolve) => {
          setTimeout(() => {
            g.notifyAmplitudeChange(g.middle, g.halfWidth);
            resolve(g);
          }, 10);
        });
      })
    );
  }
};
var FixedHalfWidthAmplitudeScale = class extends LinkedAmplitudeScale {
  constructor(halfWidth, graphList) {
    super(graphList);
    this._halfWidth = halfWidth;
  }
  recalculate() {
    return this.notifyAll();
  }
  notifyAll() {
    const hw = this.halfWidth;
    return Promise.all(
      this.graphList.map((g) => {
        return new Promise((resolve) => {
          setTimeout(() => {
            g.notifyAmplitudeChange(g.middle, hw);
            resolve(g);
          }, 10);
        });
      })
    );
  }
};
var LinkedTimeScale = class {
  constructor(graphList, originalDuration, originalOffset, scaleId) {
    this._prev_zoom_k = 1;
    this._prev_zoom_x = 0;
    if (scaleId) {
      this._scaleId = scaleId;
    } else {
      this._scaleId = -1;
    }
    const glist = graphList ? graphList : [];
    this._graphSet = new Set(glist);
    this._originalDuration = Duration.fromMillis(0);
    this._originalOffset = Duration.fromMillis(0);
    this._zoomedDuration = null;
    this._zoomedOffset = null;
    if (isDef(originalDuration)) {
      this._originalDuration = originalDuration;
      this._zoomedDuration = originalDuration;
    } else if (glist.length > 0) {
      this._originalDuration = glist.reduce((acc, cur) => {
        return acc > cur.duration ? acc : cur.duration;
      }, Duration.fromMillis(0));
    }
    if (originalOffset) {
      this._originalOffset = originalOffset;
    } else {
      this._originalOffset = Duration.fromMillis(0);
    }
    this.recalculate().catch((m) => {
      warn(`problem recalc constructor: ${m}`);
    });
  }
  /**
   * Link new TimeScalable with this time scale.
   *
   * @param   graph TimeScalable to link
   */
  link(graph) {
    this.linkAll([graph]);
  }
  /**
   * Links TimeScalable with this time scale. Each
   * object in the array should either be a TimeScalable
   * or have a time_scalable field that is a TimeScalable.
   *
   * @param   graphList Array of TimeScalable to link
   */
  linkAll(graphList) {
    graphList.forEach((graph) => {
      if ("notifyTimeRangeChange" in graph) {
        this._graphSet.add(graph);
      } else if ("time_scalable" in graph) {
        this._graphSet.add(graph.time_scalable);
      } else {
      }
    });
    this.recalculate().catch((m) => {
      warn(`problem recalc linkAll: ${m}`);
    });
  }
  /**
   * Unlink TimeScalable with this amplitude scale.
   *
   * @param   graph TimeScalable to unlink
   */
  unlink(graph) {
    this._graphSet.delete(graph);
    this.recalculate().catch((m) => {
      warn(`problem recalc unlink: ${m}`);
    });
  }
  zoom(startOffset, duration3) {
    this._zoomedDuration = duration3;
    this._zoomedOffset = startOffset;
    this.recalculate().catch((m) => {
      warn(`problem recalc zoom: ${m}`);
    });
  }
  /**
   * Return to original no-zoom zoom level
   */
  unzoom() {
    this._zoomedDuration = null;
    this._zoomedOffset = null;
    this.recalculate().catch((m) => {
      warn(`problem recalc unzoom: ${m}`);
    });
  }
  get offset() {
    return this._zoomedOffset ? this._zoomedOffset : this._originalOffset;
  }
  set offset(offset2) {
    this._originalOffset = offset2;
    this._zoomedOffset = offset2;
    this.recalculate().catch((m) => {
      warn(`problem recalc set offset: ${m}`);
    });
  }
  get duration() {
    return isDef(this._zoomedDuration) ? this._zoomedDuration : this._originalDuration;
  }
  set duration(duration3) {
    if (!isDef(duration3)) {
      throw new Error(`Duration must be defined`);
    }
    this._originalDuration = duration3;
    this._zoomedDuration = duration3;
    this.recalculate().catch((m) => {
      warn(`problem recalc set duration: ${m}`);
    });
  }
  get origOffset() {
    return this._originalOffset;
  }
  get origDuration() {
    return this._originalDuration;
  }
  /**
   * Recalculate the best time scale for all Seismographs. Causes a redraw.
   * @returns promise to array of all linked items
   */
  recalculate() {
    if (!isDef(this._zoomedDuration) || this._originalDuration.toMillis() === 0) {
      this.graphList.forEach((graph) => {
        if (graph && graph.duration > this._originalDuration) {
          this._originalDuration = graph.duration;
        }
      });
    }
    return this.notifyAll();
  }
  notifyAll() {
    return Promise.all(
      this.graphList.map((g) => {
        return new Promise((resolve) => {
          setTimeout(() => {
            if (g != null) {
              g.notifyTimeRangeChange(this.offset, this.duration);
            }
            resolve(g);
          }, 10);
        });
      })
    );
  }
  get graphList() {
    return Array.from(this._graphSet.values());
  }
};
var AlignmentLinkedTimeScale = class extends LinkedTimeScale {
  constructor(graphList, originalDuration, originalOffset, scaleId) {
    super(graphList, originalDuration, originalOffset, scaleId);
  }
  /**
   * Does no calculation, just causes a redraw.
   * @returns promise to all linked items
   */
  recalculate() {
    return this.notifyAll();
  }
  notifyAll() {
    return Promise.all(
      this.graphList.map((g) => {
        return new Promise((resolve) => {
          setTimeout(() => {
            if (g != null) {
              g.notifyTimeRangeChange(this.offset, this.duration);
            }
            resolve(g);
          }, 10);
        });
      })
    );
  }
};
var PanZoomer = class {
  constructor(target, linkedTimeScale, wheelZoom) {
    this.isMouseDown = false;
    this.wheelZoom = false;
    this._prev_zoom_k = 1;
    this._prev_zoom_x = 0;
    this.min_k = 1 / 8192;
    this.max_k = 8192;
    this._target = target;
    this.target = target;
    this.width = target.getBoundingClientRect().width;
    this.linkedTimeScale = linkedTimeScale;
    this.wheelZoom = wheelZoom ? true : false;
  }
  set target(target) {
    this._target = target;
    target.addEventListener(
      "mousedown",
      (event) => {
        const me = event;
        this.isMouseDown = true;
        this.linkedTimeScale._prev_zoom_x = me.offsetX;
      }
    );
    target.addEventListener(
      "mousemove",
      (event) => {
        const me = event;
        if (this.isMouseDown) {
          this.doZoom(this.linkedTimeScale._prev_zoom_k, me.offsetX, this.width);
        }
      }
    );
    target.addEventListener("mouseup", (_event) => {
      this.isMouseDown = false;
    });
    target.addEventListener("mouseleave", (_event) => {
      this.isMouseDown = false;
    });
    target.addEventListener("dblclick", (event) => {
      this.isMouseDown = false;
      event.preventDefault();
      const me = event;
      let factor = PHI;
      if (me.shiftKey) {
        factor = 1 / factor;
      }
      const offsetX = me.offsetX;
      this.transitionZoom(factor, offsetX);
    });
    target.addEventListener("wheel", (event) => {
      if (this.wheelZoom) {
        this.isMouseDown = false;
        const we = event;
        event.preventDefault();
        const offsetX = we.offsetX;
        this.linkedTimeScale._prev_zoom_x = offsetX;
        const factor = we.deltaY >= 0 ? SQRT_PHI : 1 / SQRT_PHI;
        this.transitionZoom(factor, offsetX, 100);
      }
    });
    this.width = target.getBoundingClientRect().width;
  }
  get target() {
    return this._target;
  }
  transitionZoom(factor, offsetX, duration3 = 250) {
    const start_k = this.linkedTimeScale._prev_zoom_k;
    const end_k = this.linkedTimeScale._prev_zoom_k * factor;
    const width = this.width;
    transition((step) => {
      const transK = start_k + (end_k - start_k) * step;
      this.doZoom(transK, offsetX, width);
    }, duration3);
  }
  doZoom(k, x2, width) {
    if (k < this.min_k) {
      k = this.min_k;
    }
    if (k > this.max_k) {
      k = this.max_k;
    }
    if (this.linkedTimeScale._prev_zoom_k === k && this.linkedTimeScale._prev_zoom_x === x2) {
      return;
    }
    const linkedTS = this.linkedTimeScale;
    const currDuration = linkedTS.duration;
    let zoomDuration = currDuration;
    const zoomDurationMillis = linkedTS.origDuration.toMillis() / k;
    let timeShift;
    if (k !== this.linkedTimeScale._prev_zoom_k) {
      zoomDuration = Duration.fromMillis(zoomDurationMillis);
      timeShift = x2 / width * (currDuration.toMillis() - zoomDurationMillis);
    } else {
      timeShift = zoomDurationMillis * (this.linkedTimeScale._prev_zoom_x - x2) / width;
      this.linkedTimeScale._prev_zoom_x = x2;
    }
    const zoomStart = linkedTS.offset.plus(Duration.fromMillis(timeShift));
    linkedTS.zoom(
      zoomStart,
      zoomDuration
    );
    this.linkedTimeScale._prev_zoom_k = k;
    this.linkedTimeScale._prev_zoom_x = x2;
  }
};

// src/seedcodec.mts
var seedcodec_exports = {};
__export(seedcodec_exports, {
  ASCII: () => ASCII,
  CDSN: () => CDSN,
  CodecException: () => CodecException,
  DOUBLE: () => DOUBLE,
  DWWSSN: () => DWWSSN,
  EncodedDataSegment: () => EncodedDataSegment,
  FLOAT: () => FLOAT,
  INT24: () => INT24,
  INTEGER: () => INTEGER,
  SHORT: () => SHORT,
  SRO: () => SRO,
  STEIM1: () => STEIM1,
  STEIM2: () => STEIM2,
  UnsupportedCompressionType: () => UnsupportedCompressionType,
  decodeSteim1: () => decodeSteim1,
  decodeSteim2: () => decodeSteim2,
  decompress: () => decompress,
  isFloatCompression: () => isFloatCompression
});
var ASCII = 0;
var SHORT = 1;
var INT24 = 2;
var INTEGER = 3;
var FLOAT = 4;
var DOUBLE = 5;
var STEIM1 = 10;
var STEIM2 = 11;
var CDSN = 16;
var SRO = 30;
var DWWSSN = 32;
var CodecException = class extends Error {
  constructor(message) {
    super(message);
    this.message = message;
    this.name = "CodecException";
  }
};
var UnsupportedCompressionType = class extends Error {
  constructor(message) {
    super(message);
    this.message = message;
    this.name = "UnsupportedCompressionType";
  }
};
function isFloatCompression(compressionType) {
  if (compressionType === FLOAT || compressionType === DOUBLE) {
    return true;
  }
  return false;
}
var EncodedDataSegment = class {
  constructor(compressionType, dataView, numSamples, littleEndian) {
    this.compressionType = compressionType;
    this.dataView = dataView;
    this.numSamples = numSamples;
    this.littleEndian = littleEndian;
  }
  isFloatCompression() {
    return isFloatCompression(this.compressionType);
  }
  decode() {
    return decompress(
      this.compressionType,
      this.dataView,
      this.numSamples,
      this.littleEndian
    );
  }
};
function decompress(compressionType, dataView, numSamples, littleEndian) {
  if (numSamples === 0) {
    return new Int32Array(0);
  }
  let out;
  let offset2 = 0;
  let i;
  switch (compressionType) {
    case SHORT:
    case DWWSSN:
      if (dataView.byteLength < 2 * numSamples) {
        throw new CodecException(
          "Not enough bytes for " + numSamples + " 16 bit data points, only " + dataView.byteLength + " bytes."
        );
      }
      out = new Int32Array(numSamples);
      for (i = 0; i < numSamples; i++) {
        out[i] = dataView.getInt16(offset2, littleEndian);
        offset2 += 2;
      }
      break;
    case INTEGER:
      if (dataView.byteLength < 4 * numSamples) {
        throw new CodecException(
          "Not enough bytes for " + numSamples + " 32 bit data points, only " + dataView.byteLength + " bytes."
        );
      }
      out = new Int32Array(numSamples);
      for (i = 0; i < numSamples; i++) {
        out[i] = dataView.getInt32(offset2, littleEndian);
        offset2 += 4;
      }
      break;
    case FLOAT:
      if (dataView.byteLength < 4 * numSamples) {
        throw new CodecException(
          "Not enough bytes for " + numSamples + " 32 bit data points, only " + dataView.byteLength + " bytes."
        );
      }
      out = new Float32Array(numSamples);
      for (i = 0; i < numSamples; i++) {
        out[i] = dataView.getFloat32(offset2, littleEndian);
        offset2 += 4;
      }
      break;
    case DOUBLE:
      if (dataView.byteLength < 8 * numSamples) {
        throw new CodecException(
          "Not enough bytes for " + numSamples + " 64 bit data points, only " + dataView.byteLength + " bytes."
        );
      }
      out = new Float64Array(numSamples);
      for (i = 0; i < numSamples; i++) {
        out[i] = dataView.getFloat64(offset2, littleEndian);
        offset2 += 8;
      }
      break;
    case STEIM1:
      out = decodeSteim1(dataView, numSamples, littleEndian, 0);
      break;
    case STEIM2:
      out = decodeSteim2(dataView, numSamples, littleEndian, 0);
      break;
    default:
      throw new UnsupportedCompressionType(
        "Type " + compressionType + " is not supported at this time."
      );
  }
  return out;
}
function decodeSteim1(dataView, numSamples, littleEndian, bias) {
  if (dataView.byteLength % 64 !== 0) {
    throw new CodecException(
      "encoded data length is not multiple of 64 bytes (" + dataView.byteLength + ")"
    );
  }
  const buf = new ArrayBuffer(4 * numSamples);
  const samples = new Int32Array(buf);
  let tempSamples;
  const numFrames = dataView.byteLength / 64;
  let current = 0;
  let start2;
  let firstData;
  let lastValue = 0;
  let i, j;
  for (i = 0; i < numFrames; i++) {
    tempSamples = extractSteim1Samples(dataView, i * 64, littleEndian);
    firstData = 0;
    if (i === 0) {
      lastValue = bias;
      start2 = tempSamples[1];
      firstData = 3;
      if (bias === 0) lastValue = start2 - tempSamples[3];
    }
    for (j = firstData; j < tempSamples.length && current < numSamples; j++) {
      samples[current] = lastValue + tempSamples[j];
      lastValue = samples[current];
      current++;
    }
  }
  if (current !== numSamples) {
    throw new CodecException(
      "Number of samples decompressed doesn't match number in header: " + current + " !== " + numSamples
    );
  }
  return samples;
}
function extractSteim1Samples(dataView, offset2, littleEndian) {
  const nibbles = dataView.getInt32(offset2, littleEndian);
  let currNibble;
  const temp = [];
  let currNum = 0;
  let i, n2;
  for (i = 0; i < 16; i++) {
    currNibble = nibbles >> 30 - i * 2 & 3;
    switch (currNibble) {
      case 0:
        if (offset2 === 0) {
          temp[currNum++] = dataView.getInt32(offset2 + i * 4, littleEndian);
        }
        break;
      case 1:
        for (n2 = 0; n2 < 4; n2++) {
          temp[currNum] = dataView.getInt8(offset2 + i * 4 + n2);
          currNum++;
        }
        break;
      case 2:
        for (n2 = 0; n2 < 4; n2 += 2) {
          temp[currNum] = dataView.getInt16(offset2 + i * 4 + n2, littleEndian);
          currNum++;
        }
        break;
      case 3:
        temp[currNum++] = dataView.getInt32(offset2 + i * 4, littleEndian);
        break;
      default:
        throw new CodecException("unreachable case: " + currNibble);
    }
  }
  return temp;
}
function decodeSteim2(dataView, numSamples, swapBytes, bias) {
  if (dataView.byteLength % 64 !== 0) {
    throw new CodecException(
      "encoded data length is not multiple of 64 bytes (" + dataView.byteLength + ")"
    );
  }
  const buf = new ArrayBuffer(4 * numSamples);
  const samples = new Int32Array(buf);
  let tempSamples;
  const numFrames = dataView.byteLength / 64;
  let current = 0;
  let start2;
  let firstData;
  let lastValue = 0;
  for (let i = 0; i < numFrames; i++) {
    tempSamples = extractSteim2Samples(dataView, i * 64, swapBytes);
    firstData = 0;
    if (i === 0) {
      lastValue = bias;
      start2 = tempSamples[1];
      firstData = 3;
      if (bias === 0) lastValue = start2 - tempSamples[3];
    }
    for (let j = firstData; j < tempSamples.length && current < numSamples; j++) {
      samples[current] = lastValue + tempSamples[j];
      lastValue = samples[current];
      current++;
    }
  }
  if (current !== numSamples) {
    throw new CodecException(
      "Number of samples decompressed doesn't match number in header: " + current + " !== " + numSamples
    );
  }
  return samples;
}
function extractSteim2Samples(dataView, offset2, swapBytes) {
  const nibbles = dataView.getUint32(offset2, swapBytes);
  let currNibble;
  let dnib;
  const temp = new Int32Array(106);
  let tempInt;
  let currNum = 0;
  let diffCount;
  let bitSize;
  let headerSize;
  for (let i = 0; i < 16; i++) {
    currNibble = nibbles >> 30 - i * 2 & 3;
    switch (currNibble) {
      case 0:
        if (offset2 === 0) {
          temp[currNum++] = dataView.getInt32(offset2 + i * 4, swapBytes);
        }
        break;
      case 1:
        temp[currNum++] = dataView.getInt8(offset2 + i * 4);
        temp[currNum++] = dataView.getInt8(offset2 + i * 4 + 1);
        temp[currNum++] = dataView.getInt8(offset2 + i * 4 + 2);
        temp[currNum++] = dataView.getInt8(offset2 + i * 4 + 3);
        break;
      case 2:
        tempInt = dataView.getUint32(offset2 + i * 4, swapBytes);
        dnib = tempInt >> 30 & 3;
        switch (dnib) {
          case 1:
            temp[currNum++] = tempInt << 2 >> 2;
            break;
          case 2:
            temp[currNum++] = tempInt << 2 >> 17;
            temp[currNum++] = tempInt << 17 >> 17;
            break;
          case 3:
            temp[currNum++] = tempInt << 2 >> 22;
            temp[currNum++] = tempInt << 12 >> 22;
            temp[currNum++] = tempInt << 22 >> 22;
            break;
          default:
            throw new CodecException(
              `Unknown case currNibble=${currNibble} dnib=${dnib} for chunk ${i} offset ${offset2}, nibbles: ${nibbles}`
            );
        }
        break;
      case 3:
        tempInt = dataView.getUint32(offset2 + i * 4, swapBytes);
        dnib = tempInt >> 30 & 3;
        switch (dnib) {
          case 0:
            headerSize = 2;
            diffCount = 5;
            bitSize = 6;
            break;
          case 1:
            headerSize = 2;
            diffCount = 6;
            bitSize = 5;
            break;
          case 2:
            headerSize = 4;
            diffCount = 7;
            bitSize = 4;
            break;
          default:
            throw new CodecException(
              `Unknown case currNibble=${currNibble} dnib=${dnib} for chunk ${i} offset ${offset2}, nibbles: ${nibbles}`
            );
        }
        if (diffCount > 0) {
          for (let d = 0; d < diffCount; d++) {
            temp[currNum++] = tempInt << headerSize + d * bitSize >> (diffCount - 1) * bitSize + headerSize;
          }
        }
        break;
      default:
        throw new CodecException(`Unknown case currNibble=${currNibble}`);
    }
  }
  return temp.slice(0, currNum);
}

// src/seismogramsegment.mts
var COUNT_UNIT = "count";
var SeismogramSegment = class _SeismogramSegment {
  constructor(yArray, sampleRate, startTime, sourceId) {
    if (yArray instanceof Int32Array || yArray instanceof Float32Array || yArray instanceof Float64Array) {
      this._y = yArray;
      this._compressed = null;
    } else if (Array.isArray(yArray) && yArray.every((ee) => ee instanceof EncodedDataSegment)) {
      this._compressed = yArray;
      this._y = null;
    } else if (Array.isArray(yArray) && yArray.every((ee) => typeof ee === "number")) {
      this._y = Float64Array.from(yArray);
      this._compressed = null;
    } else {
      this._compressed = null;
      this._y = null;
    }
    if (sampleRate <= 0) {
      throw new Error(`SampleRate must be positive number: ${sampleRate}`);
    }
    this._sampleRate = sampleRate;
    this._startTime = checkStringOrDate(startTime);
    this.yUnit = COUNT_UNIT;
    this._sourceId = sourceId ? sourceId : FDSNSourceId.createUnknown(sampleRate);
    this._endTime_cache = null;
    this._endTime_cache_numPoints = 0;
  }
  /**
   * Y data of the seismogram. Decompresses data if needed.
   *
   * @returns y data as typed array
   */
  get y() {
    let out;
    if (this._y) {
      out = this._y;
    } else {
      if (!this.isEncoded()) {
        throw new Error("Seismogram not y as TypedArray or encoded.");
      }
      const outLen = this.numPoints;
      if (this._compressed === null) {
        throw new Error("Seismogram not y as TypedArray or encoded.");
      }
      if (this._compressed[0].compressionType === DOUBLE) {
        out = new Float64Array(outLen);
      } else if (this._compressed[0].compressionType === FLOAT) {
        out = new Float32Array(outLen);
      } else {
        out = new Int32Array(outLen);
      }
      let currIdx = 0;
      for (const c of this._compressed) {
        const cData = c.decode();
        for (let i = 0; i < c.numSamples; i++) {
          out[currIdx + i] = cData[i];
        }
        currIdx += c.numSamples;
      }
      this._y = out;
      this._compressed = null;
    }
    return out;
  }
  set y(value) {
    this._y = value;
    this._invalidate_endTime_cache();
  }
  get start() {
    return this.startTime;
  }
  set start(value) {
    this.startTime = value;
  }
  get startTime() {
    return this._startTime;
  }
  set startTime(value) {
    this._startTime = checkStringOrDate(value);
    this._invalidate_endTime_cache();
  }
  get end() {
    return this.endTime;
  }
  get endTime() {
    if (!this._endTime_cache || this._endTime_cache_numPoints !== this.numPoints) {
      this._endTime_cache_numPoints = this.numPoints;
      this._endTime_cache = this.timeOfSample(
        this._endTime_cache_numPoints - 1
      );
    }
    return this._endTime_cache;
  }
  get timeRange() {
    return Interval.fromDateTimes(this.startTime, this.endTime);
  }
  get sampleRate() {
    return this._sampleRate;
  }
  set sampleRate(value) {
    this._sampleRate = value;
    this._invalidate_endTime_cache();
  }
  get samplePeriod() {
    return 1 / this.sampleRate;
  }
  get numPoints() {
    let out = 0;
    if (this._y) {
      out = this._y.length;
    } else if (this._compressed) {
      for (const c of this._compressed) {
        out += c.numSamples;
      }
    }
    return out;
  }
  get networkCode() {
    return this._sourceId.networkCode;
  }
  get stationCode() {
    return this._sourceId.stationCode;
  }
  get locationCode() {
    return this._sourceId.locationCode;
  }
  get channelCode() {
    return this._sourceId.formChannelCode();
  }
  /**
   * Checks if the data is encoded
   *
   * @returns true if encoded, false otherwise
   */
  isEncoded() {
    if (this._y && this._y.length > 0) {
      return false;
    } else if (this._compressed && this._compressed.length > 0) {
      return true;
    } else {
      return false;
    }
  }
  /**
   * Gets encoded data, if it is.
   *
   * @returns array of encoded data segments
   * @throws Error if data is not encoded
   */
  getEncoded() {
    const compressed = this._compressed;
    if (this.isEncoded() && compressed != null) {
      return compressed;
    } else {
      throw new Error("Data is not encoded.");
    }
  }
  yAtIndex(i) {
    if (i >= 0) {
      return this.y[i];
    } else {
      return this.y[this.numPoints + i];
    }
  }
  /**
   * Finds the min and max values of a SeismogramSegment, with an optional
   * accumulator for use with gappy data.
   *
   * @param minMaxAccumulator optional initialized accumulator as an array
   * of two numbers, min and max
   * @returns min, max as arry of length two
   */
  findMinMax(minMaxAccumulator) {
    let minAmp = Number.MAX_SAFE_INTEGER;
    let maxAmp = -1 * minAmp;
    if (minMaxAccumulator) {
      minAmp = minMaxAccumulator.min;
      maxAmp = minMaxAccumulator.max;
    }
    const yData = this.y;
    for (let n2 = 0; n2 < yData.length; n2++) {
      if (minAmp > yData[n2]) {
        minAmp = yData[n2];
      }
      if (maxAmp < yData[n2]) {
        maxAmp = yData[n2];
      }
    }
    return new MinMaxable(minAmp, maxAmp);
  }
  /**
   * Time of the i-th sample, indexed from zero.
   * If i is negative, counting from end, so
   * timeOfSample(-1) is time of last data point;
   *
   * @param  i               sample index
   * @returns   time
   */
  timeOfSample(i) {
    if (i >= 0) {
      return this.startTime.plus(
        Duration.fromMillis(1e3 * i / this.sampleRate)
      );
    } else {
      return this.startTime.plus(
        Duration.fromMillis(1e3 * (this.numPoints + i) / this.sampleRate)
      );
    }
  }
  indexOfTime(t) {
    if (t < this.startTime || t > this.endTime.plus(Duration.fromMillis(1e3 / this.sampleRate))) {
      return -1;
    }
    return Math.round(
      t.diff(this.startTime).toMillis() * this.sampleRate / 1e3
    );
  }
  hasCodes() {
    return isDef(this._sourceId);
  }
  /**
   * return network, station, location and channels codes as one string.
   * Uses this.channel if it exists, this.seismogram if not.
   *
   * @returns nslc codes separated by '.'
   */
  get nslc() {
    return this.codes();
  }
  get nslcId() {
    return this._sourceId.asNslc();
  }
  /**
   * return network, station, location and channels codes as one string
   *
   * @param sep separator, defaults to '.'
   * @returns nslc codes separated by sep
   */
  codes(sep = ".") {
    return (this.networkCode ? this.networkCode : "") + sep + (this.stationCode ? this.stationCode : "") + sep + (this.locationCode ? this.locationCode : "") + sep + (this.channelCode ? this.channelCode : "");
  }
  seisId() {
    const out = `${this.sourceId.toString()}_${this.startTime.toISO()}_${this.endTime.toISO()}`;
    return out.replace(/\./g, "_").replace(/:/g, "");
  }
  /**
   * return FDSN source id.
   *
   * @returns FDSN source id
   */
  get sourceId() {
    return this._sourceId;
  }
  set sourceId(sid) {
    this._sourceId = sid;
  }
  clone() {
    let out;
    if (isDef(this._y)) {
      out = this.cloneWithNewData(this._y.slice());
    } else if (this.isEncoded()) {
      out = this.cloneWithNewData(Array.from(this.getEncoded()));
    } else {
      throw new Error("no _y and no _compressed");
    }
    return out;
  }
  cloneWithNewData(clonedData, clonedStartTime = this._startTime) {
    const out = new _SeismogramSegment(
      clonedData,
      this.sampleRate,
      clonedStartTime,
      this._sourceId.clone()
    );
    out.yUnit = this.yUnit;
    return out;
  }
  cut(timeRange) {
    checkLuxonValid(timeRange);
    if (timeRange.start == null || timeRange.end == null || timeRange.end < this._startTime || timeRange.start > this.endTime) {
      return null;
    }
    let sIndex = 0;
    if (timeRange.start > this._startTime) {
      const milliDiff = timeRange.start.diff(this._startTime).toMillis();
      const offset2 = milliDiff * this.sampleRate / 1e3;
      sIndex = Math.floor(offset2);
    }
    let eIndex = this.y.length;
    if (timeRange.end < this.endTime) {
      const milliDiff = this.endTime.diff(timeRange.end).toMillis();
      const offset2 = milliDiff * this.sampleRate / 1e3;
      eIndex = this.y.length - Math.floor(offset2);
    }
    const cutY = this.y.slice(sIndex, eIndex);
    const out = this.cloneWithNewData(
      cutY,
      this._startTime.plus(
        Duration.fromMillis(1e3 * sIndex / this.sampleRate)
      )
    );
    return out;
  }
  _invalidate_endTime_cache() {
    this._endTime_cache = null;
    this._endTime_cache_numPoints = 0;
  }
};

// src/seismogram.mts
var seismogram_exports = {};
__export(seismogram_exports, {
  COUNT_UNIT: () => COUNT_UNIT2,
  NonContiguousData: () => NonContiguousData,
  Seismogram: () => Seismogram,
  SeismogramDisplayData: () => SeismogramDisplayData,
  SeismogramDisplayStats: () => SeismogramDisplayStats,
  calcMinMax: () => calcMinMax,
  ensureIsSeismogram: () => ensureIsSeismogram,
  findMaxDuration: () => findMaxDuration,
  findMaxDurationOfType: () => findMaxDurationOfType,
  findMinMax: () => findMinMax,
  findMinMaxOfSDD: () => findMinMaxOfSDD,
  findMinMaxOfSeismograms: () => findMinMaxOfSeismograms,
  findMinMaxOverRelativeTimeRange: () => findMinMaxOverRelativeTimeRange,
  findMinMaxOverTimeRange: () => findMinMaxOverTimeRange,
  findStartEnd: () => findStartEnd,
  findStartEndOfSeismograms: () => findStartEndOfSeismograms,
  uniqueBandCodes: () => uniqueBandCodes,
  uniqueChannels: () => uniqueChannels,
  uniqueLocationCodes: () => uniqueLocationCodes,
  uniqueQuakes: () => uniqueQuakes,
  uniqueSourceCodes: () => uniqueSourceCodes,
  uniqueSourceIds: () => uniqueSourceIds2,
  uniqueStations: () => uniqueStations2,
  uniqueSubsourceCodes: () => uniqueSubsourceCodes
});

// src/distaz.mts
var distaz_exports = {};
__export(distaz_exports, {
  DistAzOutput: () => DistAzOutput,
  degtokm: () => degtokm,
  distaz: () => distaz,
  kmPerDeg: () => kmPerDeg,
  kmtodeg: () => kmtodeg
});
var kmPerDeg = 111.19;
function degtokm(deg) {
  return deg * kmPerDeg;
}
function kmtodeg(km) {
  return km / kmPerDeg;
}
var DistAzOutput = class {
  constructor(delta, az, baz) {
    this.delta = delta ? delta : 0;
    this.az = az ? az : 0;
    this.baz = baz ? baz : 0;
  }
  get distance() {
    return this.delta;
  }
  get distanceKm() {
    return degtokm(this.delta);
  }
  get distanceDeg() {
    return this.delta;
  }
  get azimuth() {
    return this.az;
  }
  get backazimuth() {
    return this.baz;
  }
};
function distaz(lat1, lon1, lat2, lon2) {
  if (lat1 === lat2 && lon1 === lon2) {
    const result2 = new DistAzOutput(0, 0, 0);
    result2.stalat = lat1;
    result2.stalon = lon1;
    result2.evtlat = lat2;
    result2.evtlon = lon2;
    return result2;
  }
  const rad = 2 * Math.PI / 360;
  const sph = 1 / 298.257;
  const scolat = Math.PI / 2 - Math.atan((1 - sph) * (1 - sph) * Math.tan(lat1 * rad));
  const ecolat = Math.PI / 2 - Math.atan((1 - sph) * (1 - sph) * Math.tan(lat2 * rad));
  const slon = lon1 * rad;
  const elon = lon2 * rad;
  const a = Math.sin(scolat) * Math.cos(slon);
  const b = Math.sin(scolat) * Math.sin(slon);
  const c = Math.cos(scolat);
  const d = Math.sin(slon);
  const e = -Math.cos(slon);
  const g = -c * e;
  const h = c * d;
  const k = -Math.sin(scolat);
  const aa = Math.sin(ecolat) * Math.cos(elon);
  const bb = Math.sin(ecolat) * Math.sin(elon);
  const cc = Math.cos(ecolat);
  const dd = Math.sin(elon);
  const ee = -Math.cos(elon);
  const gg = -cc * ee;
  const hh = cc * dd;
  const kk = -Math.sin(ecolat);
  const del = Math.acos(a * aa + b * bb + c * cc);
  const result_delta = del / rad;
  const baz_rhs1 = (aa - d) * (aa - d) + (bb - e) * (bb - e) + cc * cc - 2;
  const baz_rhs2 = (aa - g) * (aa - g) + (bb - h) * (bb - h) + (cc - k) * (cc - k) - 2;
  let dbaz = Math.atan2(baz_rhs1, baz_rhs2);
  if (dbaz < 0) {
    dbaz = dbaz + 2 * Math.PI;
  }
  let result_baz = dbaz / rad;
  const daz_rhs1 = (a - dd) * (a - dd) + (b - ee) * (b - ee) + c * c - 2;
  const daz_rhs2 = (a - gg) * (a - gg) + (b - hh) * (b - hh) + (c - kk) * (c - kk) - 2;
  let daz = Math.atan2(daz_rhs1, daz_rhs2);
  if (daz < 0) {
    daz = daz + 2 * Math.PI;
  }
  let result_az = daz / rad;
  if (Math.abs(result_baz - 360) < 1e-5) result_baz = 0;
  if (Math.abs(result_az - 360) < 1e-5) result_az = 0;
  const result = new DistAzOutput(result_delta, result_az, result_baz);
  result.stalat = lat1;
  result.stalon = lon1;
  result.evtlat = lat2;
  result.evtlon = lon2;
  return result;
}

// src/stationxml.mts
var stationxml_exports = {};
__export(stationxml_exports, {
  AbstractFilterType: () => AbstractFilterType,
  Author: () => Author,
  CHANNEL_CLICK_EVENT: () => CHANNEL_CLICK_EVENT,
  COUNT_UNIT_NAME: () => COUNT_UNIT_NAME,
  Channel: () => Channel,
  CoefficientsFilter: () => CoefficientsFilter,
  Comment: () => Comment,
  DataAvailability: () => DataAvailability,
  Decimation: () => Decimation,
  Equipment: () => Equipment,
  FAKE_EMPTY_XML: () => FAKE_EMPTY_XML,
  FAKE_START_DATE: () => FAKE_START_DATE,
  FIR: () => FIR,
  FIX_INVALID_STAXML: () => FIX_INVALID_STAXML,
  Gain: () => Gain,
  INVALID_NUMBER: () => INVALID_NUMBER,
  InstrumentSensitivity: () => InstrumentSensitivity,
  Network: () => Network,
  PolesZeros: () => PolesZeros,
  Response: () => Response2,
  STAML_NS: () => STAML_NS,
  STATION_CLICK_EVENT: () => STATION_CLICK_EVENT,
  STAXML_MIME: () => STAXML_MIME,
  Span: () => Span,
  Stage: () => Stage,
  Station: () => Station,
  activeChannels: () => activeChannels,
  activeNetworks: () => activeNetworks,
  activeStations: () => activeStations,
  allChannels: () => allChannels,
  allStations: () => allStations,
  convertToAuthor: () => convertToAuthor,
  convertToChannel: () => convertToChannel,
  convertToComment: () => convertToComment,
  convertToDataAvailability: () => convertToDataAvailability,
  convertToDecimation: () => convertToDecimation,
  convertToEquipment: () => convertToEquipment,
  convertToGain: () => convertToGain,
  convertToInstrumentSensitivity: () => convertToInstrumentSensitivity,
  convertToNetwork: () => convertToNetwork,
  convertToResponse: () => convertToResponse,
  convertToStage: () => convertToStage,
  convertToStation: () => convertToStation,
  createChannelClickEvent: () => createChannelClickEvent,
  createInterval: () => createInterval,
  createStationClickEvent: () => createStationClickEvent,
  extractComplex: () => extractComplex,
  fetchStationXml: () => fetchStationXml,
  findChannels: () => findChannels,
  findChannelsForSourceId: () => findChannelsForSourceId,
  isChannelClickCustomEvent: () => isChannelClickCustomEvent,
  isStationClickCustomEvent: () => isStationClickCustomEvent,
  mightBeStatonXml: () => mightBeStatonXml,
  parseStationXml: () => parseStationXml,
  parseUtil: () => parseUtil,
  uniqueNetworks: () => uniqueNetworks,
  uniqueSourceIds: () => uniqueSourceIds,
  uniqueStations: () => uniqueStations
});

// src/oregondsputil.mts
var oregondsputil_exports = {};
__export(oregondsputil_exports, {
  Allpass: () => Allpass,
  AnalogPrototype: () => AnalogPrototype,
  BANDPASS: () => BANDPASS,
  Butterworth: () => Butterworth,
  CDFT: () => CDFT,
  CenteredDifferentiator: () => CenteredDifferentiator,
  CenteredHilbertTransform: () => CenteredHilbertTransform,
  ChebyshevI: () => ChebyshevI,
  ChebyshevII: () => ChebyshevII,
  Complex: () => Complex,
  ComplexAnalyticSignal: () => ComplexAnalyticSignal,
  EquirippleBandpass: () => EquirippleBandpass,
  EquirippleFIRFilter: () => EquirippleFIRFilter,
  EquirippleHalfBand: () => EquirippleHalfBand,
  EquirippleHighpass: () => EquirippleHighpass,
  EquirippleLowpass: () => EquirippleLowpass,
  FIRTypeI: () => FIRTypeI,
  FIRTypeII: () => FIRTypeII,
  FIRTypeIII: () => FIRTypeIII,
  HIGHPASS: () => HIGHPASS,
  HammingWindow: () => HammingWindow,
  HanningWindow: () => HanningWindow,
  IIRFilter: () => IIRFilter,
  Interpolator: () => Interpolator,
  LOWPASS: () => LOWPASS,
  LagrangePolynomial: () => LagrangePolynomial,
  OregonDSP: () => OregonDSP,
  OverlapAdd: () => OverlapAdd,
  PassbandType: () => PassbandType,
  Polynomial: () => Polynomial,
  RDFT: () => RDFT,
  Rational: () => Rational,
  Sequence: () => Sequence,
  StaggeredDifferentiator: () => StaggeredDifferentiator,
  StaggeredHilbertTranform: () => StaggeredHilbertTranform,
  ThiranAllpass: () => ThiranAllpass,
  Window: () => Window,
  complexFromPolar: () => complexFromPolar,
  createComplex: () => createComplex
});
var import_oregondsp = __toESM(require_oregondsp(), 1);
var OregonDSP = import_oregondsp.default.com.oregondsp.signalProcessing;
var fft = OregonDSP.fft;
var equiripple = OregonDSP.filter.fir.equiripple;
var fir = OregonDSP.filter.fir;
var iir = OregonDSP.filter.iir;
var CDFT = fft.CDFT;
var RDFT = fft.RDFT;
var CenteredDifferentiator = equiripple.CenteredDifferentiator;
var CenteredHilbertTransform = equiripple.CenteredHilbertTransform;
var EquirippleBandpass = equiripple.EquirippleBandpass;
var EquirippleFIRFilter = equiripple.EquirippleFIRFilter;
var EquirippleHalfBand = equiripple.EquirippleHalfBand;
var EquirippleHighpass = equiripple.EquirippleHighpass;
var EquirippleLowpass = equiripple.EquirippleLowpass;
var FIRTypeI = equiripple.FIRTypeI;
var FIRTypeII = equiripple.FIRTypeII;
var FIRTypeIII = equiripple.FIRTypeIII;
var StaggeredDifferentiator = equiripple.StaggeredDifferentiator;
var StaggeredHilbertTranform = equiripple.StaggeredHilbertTranform;
var ComplexAnalyticSignal = fir.ComplexAnalyticSignal;
var Interpolator = fir.Interpolator;
var OverlapAdd = fir.OverlapAdd;
var Allpass = iir.Allpass;
var AnalogPrototype = iir.AnalogPrototype;
var Butterworth = iir.Butterworth;
var ChebyshevI = iir.ChebyshevI;
var ChebyshevII = iir.ChebyshevII;
var Complex = iir.Complex;
var IIRFilter = iir.IIRFilter;
var PassbandType = iir.PassbandType;
var ThiranAllpass = iir.ThiranAllpass;
var LOWPASS = iir.PassbandType.LOWPASS;
var BANDPASS = iir.PassbandType.BANDPASS;
var HIGHPASS = iir.PassbandType.HIGHPASS;
var LagrangePolynomial = OregonDSP.filter.LagrangePolynomial;
var Polynomial = OregonDSP.filter.Polynomial;
var Rational = OregonDSP.filter.Rational;
var HammingWindow = OregonDSP.HammingWindow;
var HanningWindow = OregonDSP.HanningWindow;
var Sequence = OregonDSP.Sequence;
var Window = OregonDSP.Window;
function complexFromPolar(amp, phase) {
  const real = amp * Math.cos(phase);
  const imag = amp * Math.sin(phase);
  return new import_oregondsp.default.com.oregondsp.signalProcessing.filter.iir.Complex(
    real,
    imag
  );
}
function createComplex(real, imag) {
  return new import_oregondsp.default.com.oregondsp.signalProcessing.filter.iir.Complex(
    real,
    imag
  );
}

// src/stationxml.mts
var STAXML_MIME = "application/vnd.fdsn.stationxml+xml";
var STAML_NS = "http://www.fdsn.org/xml/station/1";
var COUNT_UNIT_NAME = "count";
var FIX_INVALID_STAXML = true;
var INVALID_NUMBER = -99999;
var FAKE_START_DATE = DateTime.fromISO("1900-01-01T00:00:00Z");
var FAKE_EMPTY_XML = '<?xml version="1.0" encoding="ISO-8859-1"?> <FDSNStationXML xmlns="http://www.fdsn.org/xml/station/1" schemaVersion="1.0" xsi:schemaLocation="http://www.fdsn.org/xml/station/1 http://www.fdsn.org/xml/station/fdsn-station-1.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:iris="http://www.fdsn.org/xml/station/1/iris"> </FDSNStationXML>';
var CHANNEL_CLICK_EVENT = "channelclick";
var STATION_CLICK_EVENT = "stationclick";
function isChannelClickCustomEvent(event) {
  if ("detail" in event) {
    const customEvent = event;
    return "channel" in customEvent.detail;
  }
  return false;
}
function isStationClickCustomEvent(event) {
  if ("detail" in event) {
    const customEvent = event;
    return "station" in customEvent.detail;
  }
  return false;
}
function createChannelClickEvent(sta, mouseclick) {
  const detail = {
    mouseevent: mouseclick,
    channel: sta
  };
  return new CustomEvent(
    CHANNEL_CLICK_EVENT,
    {
      detail,
      bubbles: true,
      cancelable: false,
      composed: true
    }
  );
}
function createStationClickEvent(sta, mouseclick) {
  const detail = {
    mouseevent: mouseclick,
    station: sta
  };
  return new CustomEvent(
    STATION_CLICK_EVENT,
    {
      detail,
      bubbles: true,
      cancelable: false,
      composed: true
    }
  );
}
var Network = class {
  constructor(networkCode) {
    this.networkCode = networkCode;
    this._startDate = FAKE_START_DATE;
    this._endDate = null;
    this.description = "";
    this.restrictedStatus = "";
    this.stations = [];
    this.totalNumberStations = null;
  }
  get sourceId() {
    return new NetworkSourceId(this.networkCode ? this.networkCode : "");
  }
  get startDate() {
    return this._startDate;
  }
  set startDate(value) {
    this._startDate = checkStringOrDate(value);
  }
  get endDate() {
    return this._endDate;
  }
  set endDate(value) {
    if (!isDef(value)) {
      this._endDate = null;
    } else {
      this._endDate = checkStringOrDate(value);
    }
  }
  get timeRange() {
    return createInterval(this.startDate, this.endDate);
  }
  codes() {
    return this.networkCode;
  }
  isActiveAt(d) {
    if (!isDef(d)) {
      d = DateTime.utc();
    }
    return this.timeRange.contains(d);
  }
  isTempNet() {
    const first = this.networkCode.charAt(0);
    return first === "X" || first === "Y" || first === "Z" || first >= "0" && first <= "9";
  }
};
var Station = class {
  constructor(network, stationCode) {
    this.network = network;
    this.name = "";
    this.description = "";
    this.sourceID = null;
    this.restrictedStatus = "";
    this._startDate = FAKE_START_DATE;
    this._endDate = null;
    this.stationCode = stationCode;
    this.channels = [];
    this.latitude = INVALID_NUMBER;
    this.longitude = INVALID_NUMBER;
    this.elevation = 0;
    this.waterLevel = null;
    this.comments = [];
    this.equipmentList = [];
    this.dataAvailability = null;
    this.geology = "";
    this.vault = "";
    this.identifierList = [];
  }
  get sourceId() {
    return new StationSourceId(
      this.networkCode ? this.networkCode : "",
      this.stationCode ? this.stationCode : ""
    );
  }
  get startDate() {
    return this._startDate;
  }
  set startDate(value) {
    this._startDate = checkStringOrDate(value);
  }
  get endDate() {
    return this._endDate;
  }
  set endDate(value) {
    if (!isDef(value)) {
      this._endDate = null;
    } else {
      this._endDate = checkStringOrDate(value);
    }
  }
  get timeRange() {
    return createInterval(this.startDate, this.endDate);
  }
  get networkCode() {
    return this.network.networkCode;
  }
  isActiveAt(d) {
    if (!isDef(d)) {
      d = DateTime.utc();
    }
    return this.timeRange.contains(d);
  }
  codes(sep = ".") {
    return this.network.codes() + sep + this.stationCode;
  }
};
var Channel = class {
  constructor(station, channelCode, locationCode) {
    this.waterLevel = null;
    this.comments = [];
    this.equipmentList = [];
    this.dataAvailability = null;
    this.identifierList = [];
    this.description = "";
    this.station = station;
    this._startDate = FAKE_START_DATE;
    this._endDate = null;
    this.response = null;
    this.sensor = null;
    this.preamplifier = null;
    this.datalogger = null;
    this.restrictedStatus = "";
    this.azimuth = INVALID_NUMBER;
    this.dip = INVALID_NUMBER;
    this.latitude = INVALID_NUMBER;
    this.longitude = INVALID_NUMBER;
    this.depth = 0;
    this.elevation = 0;
    this.sampleRate = 0;
    if (channelCode.length !== 3 && channelCode.split("_").length !== 3) {
      throw new Error(`Channel code must be 3 chars or of form b_s_s: "${channelCode} ${channelCode.split("_").length}"`);
    }
    this.channelCode = channelCode;
    this._locationCode = locationCode;
    if (!locationCode) {
      this._locationCode = "";
    }
    if (!(this._locationCode.length === 2 || this._locationCode.length === 0)) {
      throw new Error(
        `locationCode must be 2 chars, or empty: "${locationCode}"`
      );
    }
  }
  get sourceId() {
    if (this._sourceId) {
      return this._sourceId;
    }
    return FDSNSourceId.fromNslc(
      this.networkCode,
      this.stationCode,
      this.locationCode,
      this.channelCode
    );
  }
  set sourceId(sid) {
    this._sourceId = sid;
  }
  get nslcId() {
    return new NslcId(
      this.networkCode ? this.networkCode : "",
      this.stationCode ? this.stationCode : "",
      this.locationCode && this.locationCode !== "--" ? this.locationCode : "",
      this.channelCode ? this.channelCode : ""
    );
  }
  get startDate() {
    return this._startDate;
  }
  set startDate(value) {
    this._startDate = checkStringOrDate(value);
  }
  get endDate() {
    return this._endDate;
  }
  set endDate(value) {
    if (!isDef(value)) {
      this._endDate = null;
    } else {
      this._endDate = checkStringOrDate(value);
    }
  }
  get timeRange() {
    return createInterval(this.startDate, this.endDate);
  }
  get locationCode() {
    return this._locationCode;
  }
  set locationCode(value) {
    this._locationCode = value;
    if (!value) {
      this._locationCode = "";
    }
  }
  get stationCode() {
    return this.station.stationCode;
  }
  get networkCode() {
    return this.station.networkCode;
  }
  /**
   * Checks if this channel has sensitivity defined, within the response.
   *
   * @returns          true if instrumentSensitivity exits
   */
  hasInstrumentSensitivity() {
    return isDef(this.response) && isDef(this.response.instrumentSensitivity);
  }
  set instrumentSensitivity(value) {
    if (!isDef(this.response)) {
      this.response = new Response2(value);
    } else {
      this.response.instrumentSensitivity = value;
    }
  }
  get instrumentSensitivity() {
    if (isDef(this.response) && isDef(this.response.instrumentSensitivity)) {
      return this.response.instrumentSensitivity;
    } else {
      throw new Error("no Response or InstrumentSensitivity defined");
    }
  }
  /**
   * return network, station, location and channels codes as one string.
   *
   * @returns net.sta.loc.chan
   */
  get nslc() {
    return this.codes();
  }
  /**
   * return network, station, location and channels codes as one string.
   *
   * @param sep separator, defaults to dot '.'
   * @returns net.sta.loc.chan
   */
  codes(sep = ".") {
    return this.station.codes(sep) + sep + this.locationCode + sep + this.channelCode;
  }
  isActiveAt(d) {
    if (!isDef(d)) {
      d = DateTime.utc();
    }
    return this.timeRange.contains(d);
  }
};
var InstrumentSensitivity = class {
  constructor(sensitivity, frequency, inputUnits, outputUnits) {
    this.sensitivity = sensitivity;
    this.frequency = frequency;
    this.inputUnits = inputUnits;
    this.outputUnits = outputUnits;
  }
};
var Equipment = class {
  constructor() {
    this.resourceId = "";
    this.type = "";
    this.description = "";
    this.manufacturer = "";
    this.vendor = "";
    this.model = "";
    this.serialNumber = "";
    this.installationDate = null;
    this.removalDate = null;
    this.calibrationDateList = [];
  }
};
var Response2 = class {
  constructor(instrumentSensitivity, stages) {
    if (instrumentSensitivity) {
      this.instrumentSensitivity = instrumentSensitivity;
    } else {
      this.instrumentSensitivity = null;
    }
    if (stages) {
      this.stages = stages;
    } else {
      this.stages = [];
    }
  }
};
var Stage = class {
  constructor(filter2, decimation, gain) {
    this.filter = filter2;
    this.decimation = decimation;
    this.gain = gain;
  }
};
var AbstractFilterType = class {
  constructor(inputUnits, outputUnits) {
    this.inputUnits = inputUnits;
    this.outputUnits = outputUnits;
    this.description = "";
    this.name = "";
  }
};
var PolesZeros = class extends AbstractFilterType {
  constructor(inputUnits, outputUnits) {
    super(inputUnits, outputUnits);
    this.pzTransferFunctionType = "";
    this.normalizationFactor = 1;
    this.normalizationFrequency = 0;
    this.zeros = new Array(0);
    this.poles = new Array(0);
  }
};
var FIR = class extends AbstractFilterType {
  constructor(inputUnits, outputUnits) {
    super(inputUnits, outputUnits);
    this.symmetry = "none";
    this.numerator = [1];
  }
};
var CoefficientsFilter = class extends AbstractFilterType {
  constructor(inputUnits, outputUnits) {
    super(inputUnits, outputUnits);
    this.cfTransferFunction = "";
    this.numerator = [1];
    this.denominator = new Array(0);
  }
};
var Decimation = class {
  constructor(inputSampleRate, factor) {
    this.inputSampleRate = inputSampleRate;
    this.factor = factor;
  }
};
var Gain = class {
  constructor(value, frequency) {
    this.value = value;
    this.frequency = frequency;
  }
};
var Span = class {
  constructor(interval2) {
    this.numberSegments = 0;
    this.maximumTimeTear = null;
    this.interval = interval2;
  }
};
var DataAvailability = class {
  constructor() {
    this.extent = null;
    this.spanList = [];
  }
};
var Comment = class {
  constructor(value) {
    this.id = null;
    this.subject = null;
    this.beginEffectiveTime = null;
    this.endEffectiveTime = null;
    this.authorList = [];
    this.value = value;
  }
};
var Author = class {
  constructor() {
    this.name = null;
    this.agency = null;
    this.email = null;
    this.phone = null;
  }
};
function parseStationXml(rawXml) {
  const top2 = rawXml.documentElement;
  if (!top2) {
    throw new Error("No documentElement in XML");
  }
  const netArray = Array.from(top2.getElementsByTagNameNS(STAML_NS, "Network"));
  const out = [];
  for (const n2 of netArray) {
    out.push(convertToNetwork(n2));
  }
  return out;
}
function convertToNetwork(xml) {
  let netCode = "";
  try {
    netCode = _requireAttribute(xml, "code");
    const out = new Network(netCode);
    out.startDate = _requireAttribute(xml, "startDate");
    const rs = _grabAttribute(xml, "restrictedStatus");
    if (isNonEmptyStringArg(rs)) {
      out.restrictedStatus = rs;
    }
    const desc = _grabFirstElText(xml, "Description");
    if (isNonEmptyStringArg(desc)) {
      out.description = desc;
    }
    if (_grabAttribute(xml, "endDate")) {
      out.endDate = _grabAttribute(xml, "endDate");
    }
    const totSta = xml.getElementsByTagNameNS(STAML_NS, "TotalNumberStations");
    if (totSta && totSta.length > 0) {
      out.totalNumberStations = _grabFirstElInt(xml, "TotalNumberStations");
    }
    const staArray = Array.from(
      xml.getElementsByTagNameNS(STAML_NS, "Station")
    );
    const stations = [];
    for (const s2 of staArray) {
      stations.push(convertToStation(out, s2));
    }
    out.stations = stations;
    return out;
  } catch (err) {
    throw reErrorWithMessage(err, netCode);
  }
}
function convertToStation(network, xml) {
  let staCode = "";
  try {
    staCode = _requireAttribute(xml, "code");
    if (!isNonEmptyStringArg(staCode)) {
      throw new Error("station code missing in station!");
    }
    const out = new Station(network, staCode);
    out.startDate = _requireAttribute(xml, "startDate");
    const rs = _grabAttribute(xml, "restrictedStatus");
    if (isNonEmptyStringArg(rs)) {
      out.restrictedStatus = rs;
    }
    const lat = _grabFirstElFloat(xml, "Latitude");
    if (isNumArg(lat)) {
      out.latitude = lat;
    }
    const lon = _grabFirstElFloat(xml, "Longitude");
    if (isNumArg(lon)) {
      out.longitude = lon;
    }
    const elev = _grabFirstElFloat(xml, "Elevation");
    if (isNumArg(elev)) {
      out.elevation = elev;
    }
    const waterLevel = _grabFirstElFloat(xml, "WaterLevel");
    if (isNumArg(waterLevel)) {
      out.waterLevel = waterLevel;
    }
    const vault = _grabFirstElText(xml, "Vault");
    if (isStringArg(vault)) {
      out.vault = vault;
    }
    const geology = _grabFirstElText(xml, "Geology");
    if (isStringArg(geology)) {
      out.geology = geology;
    }
    const name = _grabFirstElText(_grabFirstEl(xml, "Site"), "Name");
    if (isStringArg(name)) {
      out.name = name;
    }
    const endDate = _grabAttribute(xml, "endDate");
    if (isDef(endDate)) {
      out.endDate = _grabAttribute(xml, "endDate");
    }
    const description = _grabFirstElText(xml, "Description");
    if (isDef(description)) {
      out.description = description;
    }
    const identifierList = Array.from(
      xml.getElementsByTagNameNS(STAML_NS, "Identifier")
    );
    out.identifierList = identifierList.map((el) => {
      return el.textContent ? el.textContent : "";
    });
    const dataAvailEl = _grabFirstEl(xml, "DataAvailability");
    if (isDef(dataAvailEl)) {
      out.dataAvailability = convertToDataAvailability(dataAvailEl);
    }
    const commentArray = Array.from(
      xml.getElementsByTagNameNS(STAML_NS, "Comment")
    );
    const comments = [];
    for (const c of commentArray) {
      comments.push(convertToComment(c));
    }
    out.comments = comments;
    const equipmentArray = Array.from(
      xml.getElementsByTagNameNS(STAML_NS, "Equipment")
    );
    const equipmentList = [];
    for (const c of equipmentArray) {
      equipmentList.push(convertToEquipment(c));
    }
    out.equipmentList = equipmentList;
    const chanArray = Array.from(
      xml.getElementsByTagNameNS(STAML_NS, "Channel")
    );
    const channels = [];
    for (const c of chanArray) {
      channels.push(convertToChannel(out, c));
    }
    out.channels = channels;
    return out;
  } catch (err) {
    throw reErrorWithMessage(err, staCode);
  }
}
function convertToChannel(station, xml) {
  let locCode = "";
  const chanCode = "";
  try {
    locCode = _grabAttribute(xml, "locationCode");
    if (!isNonEmptyStringArg(locCode)) {
      locCode = "";
    }
    const chanCode2 = _requireAttribute(xml, "code");
    const out = new Channel(station, chanCode2, locCode);
    out.startDate = checkStringOrDate(_requireAttribute(xml, "startDate"));
    const rs = _grabAttribute(xml, "restrictedStatus");
    if (isNonEmptyStringArg(rs)) {
      out.restrictedStatus = rs;
    }
    const lat = _grabFirstElFloat(xml, "Latitude");
    if (isNumArg(lat)) {
      out.latitude = lat;
    }
    const lon = _grabFirstElFloat(xml, "Longitude");
    if (isNumArg(lon)) {
      out.longitude = lon;
    }
    const elev = _grabFirstElFloat(xml, "Elevation");
    if (isNumArg(elev)) {
      out.elevation = elev;
    }
    const depth = _grabFirstElFloat(xml, "Depth");
    if (isNumArg(depth)) {
      out.depth = depth;
    }
    const waterLevel = _grabFirstElFloat(xml, "WaterLevel");
    if (isNumArg(waterLevel)) {
      out.waterLevel = waterLevel;
    }
    const azimuth = _grabFirstElFloat(xml, "Azimuth");
    if (isNumArg(azimuth)) {
      out.azimuth = azimuth;
    }
    const dip = _grabFirstElFloat(xml, "Dip");
    if (isNumArg(dip)) {
      out.dip = dip;
    }
    const desc = _grabFirstElText(xml, "Description");
    if (desc) {
      out.description = desc;
    }
    const sampleRate = _grabFirstElFloat(xml, "SampleRate");
    if (isNumArg(sampleRate)) {
      out.sampleRate = sampleRate;
    }
    if (_grabAttribute(xml, "endDate")) {
      out.endDate = _grabAttribute(xml, "endDate");
    }
    const sensor = xml.getElementsByTagNameNS(STAML_NS, "Sensor");
    if (sensor && sensor.length > 0) {
      const sensorTmp = sensor.item(0);
      if (isDef(sensorTmp)) {
        out.sensor = convertToEquipment(sensorTmp);
      }
    }
    const preamp = xml.getElementsByTagNameNS(STAML_NS, "PreAmplifier");
    if (preamp && preamp.length > 0) {
      const preampTmp = sensor.item(0);
      if (isDef(preampTmp)) {
        out.preamplifier = convertToEquipment(preampTmp);
      }
    }
    const datalogger = xml.getElementsByTagNameNS(STAML_NS, "DataLogger");
    if (datalogger && datalogger.length > 0) {
      const dataloggerTmp = sensor.item(0);
      if (isDef(dataloggerTmp)) {
        out.datalogger = convertToEquipment(dataloggerTmp);
      }
    }
    const description = _grabFirstElText(xml, "Description");
    if (isDef(description)) {
      out.description = description;
    }
    const identifierList = Array.from(
      xml.getElementsByTagNameNS(STAML_NS, "Identifier")
    );
    out.identifierList = identifierList.map((el) => {
      return el.textContent ? el.textContent : "";
    });
    const dataAvailEl = _grabFirstEl(xml, "DataAvailability");
    if (isDef(dataAvailEl)) {
      out.dataAvailability = convertToDataAvailability(dataAvailEl);
    }
    const commentArray = Array.from(
      xml.getElementsByTagNameNS(STAML_NS, "Comment")
    );
    const comments = [];
    for (const c of commentArray) {
      comments.push(convertToComment(c));
    }
    out.comments = comments;
    const equipmentArray = Array.from(
      xml.getElementsByTagNameNS(STAML_NS, "Equipment")
    );
    const equipmentList = [];
    for (const c of equipmentArray) {
      equipmentList.push(convertToEquipment(c));
    }
    out.equipmentList = equipmentList;
    const responseXml = xml.getElementsByTagNameNS(STAML_NS, "Response");
    if (responseXml && responseXml.length > 0) {
      const r = responseXml.item(0);
      if (r) {
        out.response = convertToResponse(r);
      }
    }
    return out;
  } catch (err) {
    throw reErrorWithMessage(err, `${locCode}.${chanCode}`);
  }
}
function convertToDataAvailability(xml) {
  const out = new DataAvailability();
  const extent2 = _grabFirstEl(xml, "Extent");
  if (extent2 && "start" in extent2 && "end" in extent2) {
    const s2 = _grabAttribute(extent2, "start");
    const e = _grabAttribute(extent2, "end");
    if (s2 && e) {
      out.extent = Interval.fromDateTimes(
        DateTime.fromISO(s2),
        DateTime.fromISO(e)
      );
    }
  }
  const spanArray = Array.from(xml.getElementsByTagNameNS(STAML_NS, "Span"));
  const spanList = [];
  for (const c of spanArray) {
    const s2 = _grabAttribute(c, "start");
    const e = _grabAttribute(c, "end");
    if (s2 && e) {
      const span = new Span(
        Interval.fromDateTimes(DateTime.fromISO(s2), DateTime.fromISO(e))
      );
      const numSeg = _grabAttribute(c, "numberSegments");
      if (numSeg) {
        span.numberSegments = parseInt(numSeg);
      }
      const maxTear = _grabAttribute(c, "maximumTimeTear");
      if (maxTear) {
        span.maximumTimeTear = parseFloat(maxTear);
      }
      spanList.push(span);
    }
  }
  out.spanList = spanList;
  return out;
}
function convertToComment(xml) {
  let val = _grabFirstElText(xml, "Value");
  if (!val) {
    val = "";
  }
  const out = new Comment(val);
  const id2 = _grabAttribute(xml, "id");
  if (id2) {
    out.id = id2;
  }
  const subject = _grabAttribute(xml, "subject");
  if (subject) {
    out.subject = subject;
  }
  const b = _grabFirstElText(xml, "BeginEffectiveTime");
  if (b) {
    out.beginEffectiveTime = DateTime.fromISO(b);
  }
  const e = _grabFirstElText(xml, "EndEffectiveTime");
  if (e) {
    out.endEffectiveTime = DateTime.fromISO(e);
  }
  const authList = Array.from(xml.getElementsByTagNameNS(STAML_NS, "Author"));
  out.authorList = authList.map((aEl) => convertToAuthor(aEl));
  return out;
}
function convertToAuthor(xml) {
  const out = new Author();
  const name = _grabFirstElText(xml, "Name");
  if (name) {
    out.name = name;
  }
  const agency = _grabFirstElText(xml, "Agency");
  if (agency) {
    out.agency = agency;
  }
  const phEl = _grabFirstEl(xml, "Phone");
  if (phEl) {
    out.phone = `${_grabFirstElText(phEl, "CountryCode")}-${_grabFirstElText(phEl, "AreaCode")}-${_grabFirstElText(phEl, "PhoneNumber")}`;
  }
  return out;
}
function convertToEquipment(xml) {
  const out = new Equipment();
  let val;
  val = _grabFirstElText(xml, "Type");
  if (isNonEmptyStringArg(val)) {
    out.type = val;
  }
  val = _grabFirstElText(xml, "Description");
  if (isNonEmptyStringArg(val)) {
    out.description = val;
  }
  val = _grabFirstElText(xml, "Manufacturer");
  if (isNonEmptyStringArg(val)) {
    out.manufacturer = val;
  }
  val = _grabFirstElText(xml, "Vendor");
  if (isNonEmptyStringArg(val)) {
    out.vendor = val;
  }
  val = _grabFirstElText(xml, "Model");
  if (isNonEmptyStringArg(val)) {
    out.model = val;
  }
  val = _grabFirstElText(xml, "SerialNumber");
  if (isNonEmptyStringArg(val)) {
    out.serialNumber = val;
  }
  val = _grabFirstElText(xml, "InstallationDate");
  if (isNonEmptyStringArg(val)) {
    out.installationDate = checkStringOrDate(val);
  }
  val = _grabFirstElText(xml, "RemovalDate");
  if (isNonEmptyStringArg(val)) {
    out.removalDate = checkStringOrDate(val);
  }
  const calibXml = Array.from(
    xml.getElementsByTagNameNS(STAML_NS, "CalibrationDate")
  );
  out.calibrationDateList = [];
  for (const cal of calibXml) {
    if (isDef(cal.textContent)) {
      const d = checkStringOrDate(cal.textContent);
      if (isDef(d)) {
        out.calibrationDateList.push(d);
      }
    }
  }
  return out;
}
function convertToResponse(responseXml) {
  let out = new Response2();
  const inst = responseXml.getElementsByTagNameNS(
    STAML_NS,
    "InstrumentSensitivity"
  );
  if (inst && inst.item(0)) {
    const i = inst.item(0);
    if (i) {
      out = new Response2(convertToInstrumentSensitivity(i));
    }
  }
  if (!isDef(out)) {
    out = new Response2();
  }
  const xmlStages = responseXml.getElementsByTagNameNS(STAML_NS, "Stage");
  if (xmlStages && xmlStages.length > 0) {
    const jsStages = Array.from(xmlStages).map(function(stageXml) {
      return convertToStage(stageXml);
    });
    out.stages = jsStages;
  }
  return out;
}
function convertToInstrumentSensitivity(xml) {
  const sensitivity = _grabFirstElFloat(xml, "Value");
  const frequency = _grabFirstElFloat(xml, "Frequency");
  const inputUnits = _grabFirstElText(_grabFirstEl(xml, "InputUnits"), "Name");
  let outputUnits = _grabFirstElText(_grabFirstEl(xml, "OutputUnits"), "Name");
  if (FIX_INVALID_STAXML && !isDef(outputUnits)) {
    outputUnits = COUNT_UNIT_NAME;
  }
  if (!(isDef(sensitivity) && isDef(frequency) && isDef(inputUnits) && isDef(outputUnits))) {
    throw new Error(
      `Not all elements of Sensitivity exist: ${sensitivity} ${frequency} ${inputUnits} ${outputUnits}`
    );
  }
  return new InstrumentSensitivity(
    sensitivity,
    frequency,
    inputUnits,
    outputUnits
  );
}
function convertToStage(stageXml) {
  const subEl = stageXml.firstElementChild;
  let filter2 = null;
  if (!subEl) {
    throw new Error("Stage element has no child elements");
  } else if (stageXml.childElementCount === 1 && subEl.localName === "StageGain") {
  } else {
    const inputUnits = _grabFirstElText(
      _grabFirstEl(subEl, "InputUnits"),
      "Name"
    );
    const outputUnits = _grabFirstElText(
      _grabFirstEl(subEl, "OutputUnits"),
      "Name"
    );
    if (!isNonEmptyStringArg(inputUnits)) {
      throw new Error("Stage inputUnits required");
    }
    if (!isNonEmptyStringArg(outputUnits)) {
      throw new Error("Stage outputUnits required");
    }
    if (subEl.localName === "PolesZeros") {
      const pzFilter = new PolesZeros(inputUnits, outputUnits);
      const pzt = _grabFirstElText(subEl, "PzTransferFunctionType");
      if (isNonEmptyStringArg(pzt)) {
        pzFilter.pzTransferFunctionType = pzt;
      }
      const nfa = _grabFirstElFloat(subEl, "NormalizationFactor");
      if (isNumArg(nfa)) {
        pzFilter.normalizationFactor = nfa;
      }
      const nfr = _grabFirstElFloat(subEl, "NormalizationFrequency");
      if (isNumArg(nfr)) {
        pzFilter.normalizationFrequency = nfr;
      }
      const zeros = Array.from(
        subEl.getElementsByTagNameNS(STAML_NS, "Zero")
      ).map(function(zeroEl) {
        return extractComplex(zeroEl);
      });
      const poles = Array.from(
        subEl.getElementsByTagNameNS(STAML_NS, "Pole")
      ).map(function(poleEl) {
        return extractComplex(poleEl);
      });
      pzFilter.zeros = zeros;
      pzFilter.poles = poles;
      filter2 = pzFilter;
    } else if (subEl.localName === "Coefficients") {
      const coeffXml = subEl;
      const cFilter = new CoefficientsFilter(inputUnits, outputUnits);
      const cft = _grabFirstElText(coeffXml, "CfTransferFunctionType");
      if (isNonEmptyStringArg(cft)) {
        cFilter.cfTransferFunction = cft;
      }
      cFilter.numerator = Array.from(
        coeffXml.getElementsByTagNameNS(STAML_NS, "Numerator")
      ).map(function(numerEl) {
        return isNonEmptyStringArg(numerEl.textContent) ? parseFloat(numerEl.textContent) : null;
      }).filter(isDef);
      cFilter.denominator = Array.from(
        coeffXml.getElementsByTagNameNS(STAML_NS, "Denominator")
      ).map(function(denomEl) {
        return isNonEmptyStringArg(denomEl.textContent) ? parseFloat(denomEl.textContent) : null;
      }).filter(isDef);
      filter2 = cFilter;
    } else if (subEl.localName === "ResponseList") {
      throw new Error("ResponseList not supported: ");
    } else if (subEl.localName === "FIR") {
      const firXml = subEl;
      const firFilter = new FIR(inputUnits, outputUnits);
      const s2 = _grabFirstElText(firXml, "Symmetry");
      if (isNonEmptyStringArg(s2)) {
        firFilter.symmetry = s2;
      }
      firFilter.numerator = Array.from(
        firXml.getElementsByTagNameNS(STAML_NS, "NumeratorCoefficient")
      ).map(function(numerEl) {
        return isNonEmptyStringArg(numerEl.textContent) ? parseFloat(numerEl.textContent) : null;
      }).filter(isDef);
      filter2 = firFilter;
    } else if (subEl.localName === "Polynomial") {
      throw new Error("Polynomial not supported: ");
    } else if (subEl.localName === "StageGain") {
    } else {
      throw new Error("Unknown Stage type: " + subEl.localName);
    }
    if (filter2) {
      const description = _grabFirstElText(subEl, "Description");
      if (isNonEmptyStringArg(description)) {
        filter2.description = description;
      }
      if (subEl.hasAttribute("name")) {
        const n2 = _grabAttribute(subEl, "name");
        if (isNonEmptyStringArg(n2)) {
          filter2.name = n2;
        }
      }
    }
  }
  const decimationXml = _grabFirstEl(stageXml, "Decimation");
  let decimation = null;
  if (decimationXml) {
    decimation = convertToDecimation(decimationXml);
  }
  const gainXml = _grabFirstEl(stageXml, "StageGain");
  let gain;
  if (gainXml) {
    gain = convertToGain(gainXml);
  } else {
    gain = new Gain(1, 1);
  }
  const out = new Stage(filter2, decimation, gain);
  return out;
}
function convertToDecimation(decXml) {
  let out;
  const insr = _grabFirstElFloat(decXml, "InputSampleRate");
  const fac = _grabFirstElInt(decXml, "Factor");
  if (isNumArg(insr) && isNumArg(fac)) {
    out = new Decimation(insr, fac);
  } else {
    throw new Error(
      `Decimation without InputSampleRate and Factor: ${insr} ${fac}`
    );
  }
  out.offset = _grabFirstElInt(decXml, "Offset");
  out.delay = _grabFirstElFloat(decXml, "Delay");
  out.correction = _grabFirstElFloat(decXml, "Correction");
  return out;
}
function convertToGain(gainXml) {
  let out;
  const v = _grabFirstElFloat(gainXml, "Value");
  const f = _grabFirstElFloat(gainXml, "Frequency");
  if (isNumArg(v) && isNumArg(f)) {
    out = new Gain(v, f);
  } else {
    throw new Error(`Gain does not have value and frequency: ${v} ${f}`);
  }
  return out;
}
function createInterval(start2, end) {
  if (end) {
    return Interval.fromDateTimes(start2, end);
  } else {
    return Interval.fromDateTimes(start2, WAY_FUTURE);
  }
}
function extractComplex(el) {
  const re2 = _grabFirstElFloat(el, "Real");
  const im = _grabFirstElFloat(el, "Imaginary");
  if (isNumArg(re2) && isNumArg(im)) {
    return new Complex(re2, im);
  } else {
    throw new Error(`Both Real and Imaginary required: ${re2} ${im}`);
  }
}
function* activeNetworks(networks, atTime) {
  for (const n2 of networks) {
    if (n2.isActiveAt(atTime)) {
      yield n2;
    }
  }
}
function* allStations(networks) {
  for (const n2 of networks) {
    for (const s2 of n2.stations) {
      yield s2;
    }
  }
}
function* activeStations(networks, atTime) {
  for (const s2 of allStations(networks)) {
    if (s2.isActiveAt(atTime)) {
      yield s2;
    }
  }
}
function* allChannels(networks) {
  for (const s2 of allStations(networks)) {
    for (const c of s2.channels) {
      yield c;
    }
  }
}
function* activeChannels(networks, atTime) {
  for (const c of allChannels(networks)) {
    if (c.isActiveAt(atTime)) {
      yield c;
    }
  }
}
function* findChannels(networks, netCode = ".*", staCode = ".*", locCode = ".*", chanCode = ".*") {
  if (netCode.length === 0) {
    netCode = ".*";
  }
  const netRE = new RegExp(`^${netCode}$`);
  if (staCode.length === 0) {
    staCode = ".*";
  }
  const staRE = new RegExp(`^${staCode}$`);
  if (locCode.length === 0) {
    locCode = ".*";
  }
  const locRE = new RegExp(`^${locCode}$`);
  if (chanCode.length === 0) {
    chanCode = ".*";
  }
  const chanRE = new RegExp(`^${chanCode}$`);
  for (const n2 of networks.filter((n3) => netRE.test(n3.networkCode))) {
    for (const s2 of n2.stations.filter((s3) => staRE.test(s3.stationCode))) {
      for (const c of s2.channels.filter(
        (c2) => locRE.test(c2.locationCode) && chanRE.test(c2.channelCode)
      )) {
        yield c;
      }
    }
  }
}
function* findChannelsForSourceId(networks, sid) {
  const netRE = new RegExp(`^${sid.networkCode}$`);
  const staRE = new RegExp(`^${sid.stationCode}$`);
  const locRE = new RegExp(`^${sid.locationCode}$`);
  const bandRE = new RegExp(`^${sid.bandCode}$`);
  const sourceRE = new RegExp(`^${sid.sourceCode}$`);
  const subsourceRE = new RegExp(`^${sid.subsourceCode}$`);
  for (const n2 of networks.filter((n3) => netRE.test(n3.networkCode))) {
    for (const s2 of n2.stations.filter((s3) => staRE.test(s3.stationCode))) {
      for (const c of s2.channels.filter(
        (c2) => locRE.test(c2.locationCode)
      )) {
        const chanSid = c.sourceId;
        if (bandRE.test(chanSid.bandCode) && sourceRE.test(chanSid.sourceCode) && subsourceRE.test(chanSid.subsourceCode)) {
          yield c;
        }
      }
    }
  }
}
function uniqueSourceIds(channelList) {
  const out = /* @__PURE__ */ new Map();
  for (const c of channelList) {
    if (c) {
      out.set(c.sourceId.toString(), c.sourceId);
    }
  }
  return Array.from(out.values()).sort(SourceIdSorter);
}
function uniqueStations(channelList) {
  const out = /* @__PURE__ */ new Set();
  for (const c of channelList) {
    if (c) {
      out.add(c.station);
    }
  }
  return Array.from(out.values());
}
function uniqueNetworks(channelList) {
  const out = /* @__PURE__ */ new Set();
  for (const c of channelList) {
    if (c) {
      if (c instanceof Station) {
        out.add(c.network);
      } else if (c instanceof Channel) {
        out.add(c.station.network);
      } else {
        throw new Error(`unknown type for uniqueNetworks: ${c}`);
      }
    }
  }
  return Array.from(out.values());
}
function fetchStationXml(url2, timeoutSec2 = 10, nodata = 204) {
  const fetchInit = defaultFetchInitObj(XML_MIME);
  return doFetchWithTimeout(url2, fetchInit, timeoutSec2 * 1e3).then((response) => {
    if (response.status === 200) {
      return response.text();
    } else if (response.status === 204 || isDef(nodata) && response.status === nodata) {
      return FAKE_EMPTY_XML;
    } else {
      throw new Error(`Status not successful: ${response.status}`);
    }
  }).then(function(rawXmlText) {
    return new DOMParser().parseFromString(rawXmlText, XML_MIME);
  }).then((rawXml) => {
    return parseStationXml(rawXml);
  });
}
function mightBeStatonXml(buf) {
  if (!mightBeXml(buf)) {
    return false;
  }
  const initialChars = dataViewToString(new DataView(buf.slice(0, 100))).trimStart();
  if (!initialChars.includes("FDSNStationXML")) {
    return false;
  }
  return true;
}
var _grabFirstEl = function(xml, tagName) {
  if (xml instanceof Element) {
    const elList = Array.from(xml.children).filter(
      (e) => e.tagName === tagName
    );
    if (elList.length > 0) {
      const e = elList[0];
      if (e) {
        return e;
      }
    }
  }
  return null;
};
var _grabFirstElText = function _grabFirstElText2(xml, tagName) {
  let out = null;
  const el = _grabFirstEl(xml, tagName);
  if (el instanceof Element) {
    out = el.textContent;
  }
  return out;
};
var _grabFirstElFloat = function _grabFirstElFloat2(xml, tagName) {
  let out = null;
  const elText = _grabFirstElText(xml, tagName);
  if (isStringArg(elText)) {
    out = parseFloat(elText);
  }
  return out;
};
var _grabFirstElInt = function _grabFirstElInt2(xml, tagName) {
  let out = null;
  const elText = _grabFirstElText(xml, tagName);
  if (isStringArg(elText)) {
    out = parseInt(elText);
  }
  return out;
};
var _grabAttribute = function _grabAttribute2(xml, tagName) {
  let out = null;
  if (xml instanceof Element) {
    const a = xml.getAttribute(tagName);
    if (isStringArg(a)) {
      out = a;
    }
  }
  return out;
};
var _requireAttribute = function _requireAttribute2(xml, tagName) {
  const out = _grabAttribute(xml, tagName);
  if (typeof out !== "string") {
    throw new Error(`Attribute ${tagName} not found.`);
  }
  return out;
};
var _grabAttributeNS = function(xml, namespace, tagName) {
  let out = null;
  if (xml instanceof Element) {
    const a = xml.getAttributeNS(namespace, tagName);
    if (isStringArg(a)) {
      out = a;
    }
  }
  return out;
};
var parseUtil = {
  _grabFirstEl,
  _grabFirstElText,
  _grabFirstElFloat,
  _grabFirstElInt,
  _grabAttribute,
  _requireAttribute,
  _grabAttributeNS
};

// src/quakeml.mts
var quakeml_exports = {};
__export(quakeml_exports, {
  ANSS_CATALOG_NS: () => ANSS_CATALOG_NS,
  ANSS_NS: () => ANSS_NS,
  Amplitude: () => Amplitude,
  Arrival: () => Arrival,
  Axis: () => Axis,
  BED_NS: () => BED_NS,
  Comment: () => Comment2,
  CompositeTime: () => CompositeTime,
  ConfidenceEllipsoid: () => ConfidenceEllipsoid,
  CreationInfo: () => CreationInfo,
  DataUsed: () => DataUsed,
  EventDescription: () => EventDescription,
  EventParameters: () => EventParameters,
  FAKE_EMPTY_XML: () => FAKE_EMPTY_XML2,
  FAKE_ORIGIN_TIME: () => FAKE_ORIGIN_TIME,
  FocalMechanism: () => FocalMechanism,
  IRIS_NS: () => IRIS_NS,
  Magnitude: () => Magnitude,
  MomentTensor: () => MomentTensor,
  NodalPlane: () => NodalPlane,
  NodalPlanes: () => NodalPlanes,
  Origin: () => Origin,
  OriginQuality: () => OriginQuality,
  OriginUncertainty: () => OriginUncertainty,
  Pick: () => Pick,
  PrincipalAxes: () => PrincipalAxes,
  QML_NS: () => QML_NS,
  QUAKE_CLICK_EVENT: () => QUAKE_CLICK_EVENT,
  Quake: () => Quake,
  Quantity: () => Quantity,
  SourceTimeFunction: () => SourceTimeFunction,
  StationMagnitude: () => StationMagnitude,
  StationMagnitudeContribution: () => StationMagnitudeContribution,
  Tensor: () => Tensor,
  TimeWindow: () => TimeWindow,
  UNKNOWN_MAG_TYPE: () => UNKNOWN_MAG_TYPE,
  UNKNOWN_PUBLIC_ID: () => UNKNOWN_PUBLIC_ID,
  USGS_HOST: () => USGS_HOST,
  WaveformID: () => WaveformID,
  ZERO_MAGNITUDE: () => ZERO_MAGNITUDE,
  createQuakeClickEvent: () => createQuakeClickEvent,
  createQuakeFromValues: () => createQuakeFromValues,
  createUnknownId: () => createUnknownId,
  fetchQuakeML: () => fetchQuakeML,
  isQuakeClickCustomEvent: () => isQuakeClickCustomEvent,
  mightBeQuakeML: () => mightBeQuakeML,
  parseQuakeML: () => parseQuakeML,
  parseUtil: () => parseUtil2
});

// src/textformat.mts
var lang = typeof navigator !== "undefined" && navigator?.language ? navigator?.language : "en-US";
var latlonFormat = new Intl.NumberFormat(lang, {
  style: "unit",
  unit: "degree",
  unitDisplay: "narrow",
  maximumFractionDigits: 2
});
var magFormat = new Intl.NumberFormat(lang, {
  style: "decimal",
  maximumFractionDigits: 2
});
var depthNoUnitFormat = new Intl.NumberFormat(lang, {
  style: "decimal",
  maximumFractionDigits: 2
});
var depthFormat = new Intl.NumberFormat(lang, {
  style: "unit",
  unit: "kilometer",
  unitDisplay: "narrow",
  maximumFractionDigits: 2,
  minimumFractionDigits: 2
});
var depthMeterFormat = new Intl.NumberFormat(lang, {
  style: "unit",
  unit: "meter",
  unitDisplay: "narrow",
  maximumFractionDigits: 1,
  minimumFractionDigits: 1
});

// src/quakeml.mts
var QML_NS = "http://quakeml.org/xmlns/quakeml/1.2";
var BED_NS = "http://quakeml.org/xmlns/bed/1.2";
var IRIS_NS = "http://service.iris.edu/fdsnws/event/1/";
var ANSS_NS = "http://anss.org/xmlns/event/0.1";
var ANSS_CATALOG_NS = "http://anss.org/xmlns/catalog/0.1";
var USGS_HOST = "earthquake.usgs.gov";
var UNKNOWN_MAG_TYPE = "unknown";
var UNKNOWN_PUBLIC_ID = "unknownId";
var FAKE_ORIGIN_TIME = DateTime.fromISO("1900-01-01T00:00:00Z");
var FAKE_EMPTY_XML2 = '<?xml version="1.0"?><q:quakeml xmlns="http://quakeml.org/xmlns/bed/1.2" xmlns:q="http://quakeml.org/xmlns/quakeml/1.2"><eventParameters publicID="quakeml:fake/empty"></eventParameters></q:quakeml>';
var QUAKE_CLICK_EVENT = "quakeclick";
function isQuakeClickCustomEvent(event) {
  if ("detail" in event) {
    const customEvent = event;
    return "quake" in customEvent.detail;
  }
  return false;
}
function createQuakeClickEvent(q, mouseclick) {
  const detail = {
    mouseevent: mouseclick,
    quake: q
  };
  return new CustomEvent(
    QUAKE_CLICK_EVENT,
    {
      detail,
      bubbles: true,
      cancelable: false,
      composed: true
    }
  );
}
var BaseElement = class {
  constructor() {
    this.publicId = UNKNOWN_PUBLIC_ID;
    this.comments = [];
  }
  populate(qml) {
    let pid = _grabAttribute3(qml, "publicID");
    if (!isNonEmptyStringArg(pid)) {
      warn(`missing publicID on ${qml.localName}`);
      pid = `${createUnknownId()}_${qml.localName}`;
    }
    this.publicId = pid;
    this.comments = _grabAllElComment(qml, "comment");
    this.creationInfo = _grabFirstElCreationInfo(qml, "creationInfo");
  }
};
var EventParameters = class _EventParameters extends BaseElement {
  constructor() {
    super(...arguments);
    this.eventList = [];
  }
  /**
   * Parses a QuakeML event parameters xml element into an EventParameters object.
   *
   * @param eventParametersQML the event parameters xml Element
   * @param host optional source of the xml, helpful for parsing the eventid
   * @returns EventParameters instance
   */
  static createFromXml(eventParametersQML, host) {
    if (eventParametersQML.localName !== "eventParameters") {
      throw new Error(
        `Cannot extract, not a QuakeML event parameters: ${eventParametersQML.localName}`
      );
    }
    const eventEls = Array.from(
      eventParametersQML.getElementsByTagNameNS(BED_NS, "event")
    );
    const events = eventEls.map((e) => Quake.createFromXml(e, host));
    const description = _grabFirstElText3(eventParametersQML, "description");
    const out = new _EventParameters();
    out.populate(eventParametersQML);
    out.eventList = events;
    out.description = description;
    return out;
  }
};
var Quake = class _Quake extends BaseElement {
  constructor() {
    super(...arguments);
    this.descriptionList = [];
    this.amplitudeList = [];
    this.stationMagnitudeList = [];
    this.magnitudeList = [];
    this.originList = [];
    this.pickList = [];
    this.focalMechanismList = [];
  }
  /**
   * Parses a QuakeML event xml element into a Quake object. Pass in
   * host=seisplotjs.fdsnevent.USGS_HOST for xml from the USGS service
   * in order to parse the eventid, otherwise this can be left out
   *
   * @param qml the event xml Element
   * @param host optional source of the xml, helpful for parsing the eventid
   * @returns QuakeML Quake(Event) object
   */
  static createFromXml(qml, host) {
    if (qml.localName !== "event") {
      throw new Error(`Cannot extract, not a QuakeML Event: ${qml.localName}`);
    }
    const out = new _Quake();
    out.populate(qml);
    const descriptionEls = Array.from(qml.children).filter(
      (e) => e.tagName === "description"
    );
    out.descriptionList = descriptionEls.map(
      (d) => EventDescription.createFromXml(d)
    );
    const allPickEls = Array.from(qml.getElementsByTagNameNS(BED_NS, "pick"));
    const allPicks = [];
    for (const pickEl of allPickEls) {
      allPicks.push(Pick.createFromXml(pickEl));
    }
    const allAmplitudeEls = Array.from(
      qml.getElementsByTagNameNS(BED_NS, "amplitude")
    );
    const allAmplitudes = [];
    for (const amplitudeEl of allAmplitudeEls) {
      allAmplitudes.push(Amplitude.createFromXml(amplitudeEl, allPicks));
    }
    const allOriginEls = Array.from(
      qml.getElementsByTagNameNS(BED_NS, "origin")
    );
    const allOrigins = [];
    for (const originEl of allOriginEls) {
      try {
        allOrigins.push(Origin.createFromXml(originEl, allPicks));
      } catch (err) {
        const pubId = originEl.getAttribute("publicID");
        console.warn(`Parse error for origin, skipping. Id: ${pubId}  ${err}`);
      }
    }
    const allStationMagEls = Array.from(
      qml.getElementsByTagNameNS(BED_NS, "stationMagnitude")
    );
    const allStationMags = [];
    for (const stationMagEl of allStationMagEls) {
      allStationMags.push(
        StationMagnitude.createFromXml(stationMagEl, allOrigins, allAmplitudes)
      );
    }
    const allMagEls = Array.from(
      qml.getElementsByTagNameNS(BED_NS, "magnitude")
    );
    const allMags = [];
    for (const magEl of allMagEls) {
      allMags.push(Magnitude.createFromXml(magEl, allOrigins, allStationMags));
    }
    const allFocalMechEls = Array.from(
      qml.getElementsByTagNameNS(BED_NS, "focalMechanism")
    );
    const allFocalMechs = [];
    for (const focalMechEl of allFocalMechEls) {
      allFocalMechs.push(
        FocalMechanism.createFromXml(focalMechEl, allOrigins, allMags)
      );
    }
    out.originList = allOrigins;
    out.magnitudeList = allMags;
    out.pickList = allPicks;
    out.amplitudeList = allAmplitudes;
    out.stationMagnitudeList = allStationMags;
    out.focalMechanismList = allFocalMechs;
    out.eventId = _Quake.extractEventId(qml, host);
    const preferredOriginId = _grabFirstElText3(qml, "preferredOriginID");
    const preferredMagnitudeId = _grabFirstElText3(qml, "preferredMagnitudeID");
    const preferredFocalMechId = _grabFirstElText3(
      qml,
      "preferredFocalMechanismID"
    );
    if (isNonEmptyStringArg(preferredOriginId)) {
      out.preferredOrigin = allOrigins.find(
        (o) => o.publicId === preferredOriginId
      );
      if (!out.preferredOrigin) {
        throw new Error(`no preferredOriginId match: ${preferredOriginId}`);
      }
    }
    if (isNonEmptyStringArg(preferredMagnitudeId)) {
      out.preferredMagnitude = allMags.find(
        (m) => m.publicId === preferredMagnitudeId
      );
      if (!out.preferredMagnitude) {
        throw new Error(`no match: ${preferredMagnitudeId}`);
      }
    }
    if (isNonEmptyStringArg(preferredFocalMechId)) {
      out.preferredFocalMechanism = allFocalMechs.find(
        (m) => m.publicId === preferredFocalMechId
      );
      if (!out.preferredFocalMechanism) {
        throw new Error(`no match: ${preferredFocalMechId}`);
      }
    }
    out.type = _grabFirstElText3(qml, "type");
    out.typeCertainty = _grabFirstElText3(qml, "typeCertainty");
    return out;
  }
  /**
   * Extracts the EventId from a QuakeML element, guessing from one of several
   * incompatible (grumble grumble) formats.
   *
   * @param   qml Quake(Event) to extract from
   * @param   host optional source of the xml to help determine the event id style
   * @returns     Extracted Id, or "unknownEventId" if we can't figure it out
   */
  static extractEventId(qml, _host) {
    const dataId = _grabAttributeNS2(qml, ANSS_CATALOG_NS, "dataid");
    if (isNonEmptyStringArg(dataId)) {
      return dataId;
    }
    const eventId = _grabAttributeNS2(qml, ANSS_CATALOG_NS, "eventid");
    const catalogEventSource = _grabAttributeNS2(
      qml,
      ANSS_CATALOG_NS,
      "eventsource"
    );
    if (isNonEmptyStringArg(eventId)) {
      if (isNonEmptyStringArg(catalogEventSource)) {
        return catalogEventSource + eventId;
      } else {
        return eventId;
      }
    }
    const publicid = _grabAttribute3(qml, "publicID");
    if (isNonEmptyStringArg(publicid)) {
      let re2 = /eventid=([\w\d]+)/;
      let parsed = re2.exec(publicid);
      if (parsed) {
        return parsed[1];
      }
      re2 = /evid=([\w\d]+)/;
      parsed = re2.exec(publicid);
      if (parsed) {
        return parsed[1];
      }
      re2 = /quakeml:se.anss.org\/Event\/([\w\d]+)\/([\w\d]+)/;
      parsed = re2.exec(publicid);
      if (parsed) {
        return parsed[1] + parsed[2];
      }
      return publicid;
    }
    return createUnknownId();
  }
  hasPreferredOrigin() {
    return isDef(this.preferredOrigin);
  }
  hasOrigin() {
    return isDef(this.preferredOrigin) || this.originList.length > 1;
  }
  get origin() {
    if (isDef(this.preferredOrigin)) {
      return this.preferredOrigin;
    } else if (this.originList.length > 0) {
      return this.originList[0];
    } else {
      throw new Error("No origins in quake");
    }
  }
  hasPreferredMagnitude() {
    return isDef(this.preferredMagnitude);
  }
  hasMagnitude() {
    return isDef(this.preferredMagnitude) || this.magnitudeList.length > 1;
  }
  get magnitude() {
    if (isDef(this.preferredMagnitude)) {
      return this.preferredMagnitude;
    } else if (this.magnitudeList.length > 0) {
      return this.magnitudeList[0];
    } else {
      return ZERO_MAGNITUDE;
    }
  }
  get time() {
    return this.origin.time;
  }
  get latitude() {
    return this.origin.latitude;
  }
  get longitude() {
    return this.origin.longitude;
  }
  get depth() {
    return this.origin.depth;
  }
  get depthKm() {
    return this.depth / 1e3;
  }
  get description() {
    return this.descriptionList.length > 0 ? this.descriptionList[0].text : "";
  }
  get arrivals() {
    return this.origin.arrivalList;
  }
  get picks() {
    return this.pickList;
  }
  toString() {
    if (this.hasOrigin()) {
      const magStr = this.hasMagnitude() ? this.magnitude.toString() : "";
      const latlon = `(${latlonFormat.format(this.latitude)}/${latlonFormat.format(this.longitude)})`;
      const depth = depthFormat.format(this.depth / 1e3);
      return `${this.time.toISO()} ${latlon} ${depth} ${magStr}`;
    } else if (this.eventId != null) {
      return `Event: ${this.eventId}`;
    } else {
      return `Event: unknown`;
    }
  }
};
var EventDescription = class _EventDescription {
  constructor(text) {
    this.text = text;
  }
  /**
   * Parses a QuakeML description xml element into a EventDescription object.
   *
   * @param descriptionQML the description xml Element
   * @returns EventDescription instance
   */
  static createFromXml(descriptionQML) {
    if (descriptionQML.localName !== "description") {
      throw new Error(
        `Cannot extract, not a QuakeML description ID: ${descriptionQML.localName}`
      );
    }
    const text = _grabFirstElText3(descriptionQML, "text");
    if (!isNonEmptyStringArg(text)) {
      throw new Error("description missing text");
    }
    const out = new _EventDescription(text);
    out.type = _grabFirstElText3(descriptionQML, "type");
    return out;
  }
  toString() {
    return this.text;
  }
};
var Amplitude = class _Amplitude extends BaseElement {
  constructor(genericAmplitude) {
    super();
    this.genericAmplitude = genericAmplitude;
  }
  /**
   * Parses a QuakeML amplitude xml element into an Amplitude object.
   *
   * @param amplitudeQML the amplitude xml Element
   * @param allPicks picks already extracted from the xml for linking arrivals with picks
   * @returns Amplitude instance
   */
  static createFromXml(amplitudeQML, allPicks) {
    if (amplitudeQML.localName !== "amplitude") {
      throw new Error(
        `Cannot extract, not a QuakeML amplitude: ${amplitudeQML.localName}`
      );
    }
    const genericAmplitude = _grabFirstElRealQuantity(
      amplitudeQML,
      "genericAmplitude"
    );
    if (!isDef(genericAmplitude)) {
      throw new Error("amplitude missing genericAmplitude");
    }
    const out = new _Amplitude(genericAmplitude);
    out.populate(amplitudeQML);
    out.type = _grabFirstElText3(amplitudeQML, "type");
    out.category = _grabFirstElText3(amplitudeQML, "category");
    out.unit = _grabFirstElText3(amplitudeQML, "unit");
    out.methodID = _grabFirstElText3(amplitudeQML, "methodID");
    out.period = _grabFirstElRealQuantity(amplitudeQML, "period");
    out.snr = _grabFirstElFloat3(amplitudeQML, "snr");
    out.timeWindow = _grabFirstElType(
      TimeWindow.createFromXml.bind(TimeWindow)
    )(amplitudeQML, "timeWindow");
    const pickID = _grabFirstElText3(amplitudeQML, "pickID");
    out.pick = allPicks.find((p) => p.publicId === pickID);
    if (pickID && !out.pick) {
      throw new Error("No pick with ID " + pickID);
    }
    out.waveformID = _grabFirstElType(
      WaveformID.createFromXml.bind(WaveformID)
    )(amplitudeQML, "waveformID");
    out.filterID = _grabFirstElText3(amplitudeQML, "filterID");
    out.scalingTime = _grabFirstElTimeQuantity(amplitudeQML, "scalingTime");
    out.magnitudeHint = _grabFirstElText3(amplitudeQML, "magnitudeHint");
    out.evaluationMode = _grabFirstElText3(amplitudeQML, "evaluationMode");
    out.evaluationStatus = _grabFirstElText3(amplitudeQML, "evaluationStatus");
    return out;
  }
};
var StationMagnitude = class _StationMagnitude extends BaseElement {
  constructor(origin, mag) {
    super();
    this.origin = origin;
    this.mag = mag;
  }
  /**
   * Parses a QuakeML station magnitude xml element into a StationMagnitude object.
   *
   * @param stationMagnitudeQML the station magnitude xml Element
   * @param allOrigins origins already extracted from the xml for linking station magnitudes with origins
   * @param allAmplitudes amplitudes already extracted from the xml for linking station magnitudes with amplitudes
   * @returns StationMagnitude instance
   */
  static createFromXml(stationMagnitudeQML, allOrigins, allAmplitudes) {
    if (stationMagnitudeQML.localName !== "stationMagnitude") {
      throw new Error(
        `Cannot extract, not a QuakeML station magnitude: ${stationMagnitudeQML.localName}`
      );
    }
    const originID = _grabFirstElText3(stationMagnitudeQML, "originID");
    if (!isNonEmptyStringArg(originID)) {
      throw new Error("stationMagnitude missing origin ID");
    }
    const origin = allOrigins.find((o) => o.publicId === originID);
    if (!isDef(origin)) {
      throw new Error("No origin with ID " + originID);
    }
    const mag = _grabFirstElRealQuantity(stationMagnitudeQML, "mag");
    if (!isDef(mag)) {
      throw new Error("stationMagnitude missing mag");
    }
    const out = new _StationMagnitude(origin, mag);
    out.populate(stationMagnitudeQML);
    out.type = _grabFirstElText3(stationMagnitudeQML, "type");
    const amplitudeID = _grabFirstElText3(stationMagnitudeQML, "amplitudeID");
    out.amplitude = allAmplitudes.find((a) => a.publicId === amplitudeID);
    if (amplitudeID && !out.amplitude) {
      throw new Error("No amplitude with ID " + amplitudeID);
    }
    out.methodID = _grabFirstElText3(stationMagnitudeQML, "methodID");
    out.waveformID = _grabFirstElType(
      WaveformID.createFromXml.bind(WaveformID)
    )(stationMagnitudeQML, "waveformID");
    return out;
  }
};
var TimeWindow = class _TimeWindow {
  constructor(begin, end, reference) {
    this.begin = begin;
    this.end = end;
    this.reference = reference;
  }
  /**
   * Parses a QuakeML time window xml element into a TimeWindow object.
   *
   * @param timeWindowQML the time window xml Element
   * @returns TimeWindow instance
   */
  static createFromXml(timeWindowQML) {
    if (timeWindowQML.localName !== "timeWindow") {
      throw new Error(
        `Cannot extract, not a QuakeML time window: ${timeWindowQML.localName}`
      );
    }
    const begin = _grabFirstElFloat3(timeWindowQML, "begin");
    if (!isDef(begin)) {
      throw new Error("timeWindow missing begin");
    }
    const end = _grabFirstElFloat3(timeWindowQML, "end");
    if (!isDef(end)) {
      throw new Error("timeWindow missing end");
    }
    const reference = _grabFirstElDateTime(timeWindowQML, "reference");
    if (!isDef(reference)) {
      throw new Error("timeWindow missing reference");
    }
    const out = new _TimeWindow(begin, end, reference);
    return out;
  }
};
var Origin = class _Origin extends BaseElement {
  constructor(time3, latitude, longitude) {
    super();
    this.compositeTimes = [];
    this.arrivalList = [];
    if (time3 instanceof DateTime) {
      this.timeQuantity = new Quantity(time3);
    } else {
      this.timeQuantity = time3;
    }
    if (typeof latitude == "number") {
      this.latitudeQuantity = new Quantity(latitude);
    } else {
      this.latitudeQuantity = latitude;
    }
    if (typeof longitude == "number") {
      this.longitudeQuantity = new Quantity(longitude);
    } else {
      this.longitudeQuantity = longitude;
    }
  }
  /**
   * Parses a QuakeML origin xml element into a Origin object.
   *
   * @param qml the origin xml Element
   * @param allPicks picks already extracted from the xml for linking arrivals with picks
   * @returns Origin instance
   */
  static createFromXml(qml, allPicks) {
    if (qml.localName !== "origin") {
      throw new Error(`Cannot extract, not a QuakeML Origin: ${qml.localName}`);
    }
    const time3 = _grabFirstElTimeQuantity(qml, "time");
    if (!isObject(time3)) {
      throw new Error("origin missing time");
    }
    const lat = _grabFirstElRealQuantity(qml, "latitude");
    if (!isObject(lat)) {
      throw new Error("origin missing latitude");
    }
    const lon = _grabFirstElRealQuantity(qml, "longitude");
    if (!isObject(lon)) {
      throw new Error("origin missing longitude");
    }
    const out = new _Origin(time3, lat, lon);
    out.populate(qml);
    out.originUncertainty = _grabFirstElType(
      OriginUncertainty.createFromXml.bind(OriginUncertainty)
    )(qml, "originUncertainty");
    const allArrivalEls = Array.from(
      qml.getElementsByTagNameNS(BED_NS, "arrival")
    );
    out.arrivalList = allArrivalEls.map(
      (arrivalEl) => Arrival.createFromXml(arrivalEl, allPicks)
    );
    out.depthQuantity = _grabFirstElRealQuantity(qml, "depth");
    out.depthType = _grabFirstElText3(qml, "depthType");
    out.timeFixed = _grabFirstElBool(qml, "timeFixed");
    out.epicenterFixed = _grabFirstElBool(qml, "epicenterFixed");
    out.referenceSystemID = _grabFirstElText3(qml, "referenceSystemID");
    out.methodID = _grabFirstElText3(qml, "methodID");
    out.earthModelID = _grabFirstElText3(qml, "earthModelID");
    out.quality = _grabFirstElType(
      OriginQuality.createFromXml.bind(OriginQuality)
    )(qml, "quality");
    out.type = _grabFirstElText3(qml, "type");
    out.region = _grabFirstElText3(qml, "region");
    out.evaluationMode = _grabFirstElText3(qml, "evaluationMode");
    out.evaluationStatus = _grabFirstElText3(qml, "evaluationStatus");
    return out;
  }
  toString() {
    const latlon = `(${latlonFormat.format(this.latitude)}/${latlonFormat.format(this.longitude)})`;
    const depth = depthFormat.format(this.depth / 1e3);
    return `${this.time.toISO()} ${latlon} ${depth} km`;
  }
  get time() {
    return this.timeQuantity.value;
  }
  set time(t) {
    if (t instanceof DateTime) {
      this.timeQuantity.value = t;
    } else {
      this.timeQuantity = t;
    }
  }
  get latitude() {
    return this.latitudeQuantity.value;
  }
  set latitude(lat) {
    if (typeof lat == "number") {
      this.latitudeQuantity.value = lat;
    } else {
      this.latitudeQuantity = lat;
    }
  }
  get longitude() {
    return this.longitudeQuantity.value;
  }
  set longitude(lon) {
    if (typeof lon == "number") {
      this.longitudeQuantity.value = lon;
    } else {
      this.longitudeQuantity = lon;
    }
  }
  get depthKm() {
    return this.depth / 1e3;
  }
  get depth() {
    return this.depthQuantity?.value ?? NaN;
  }
  set depth(depth) {
    if (typeof depth == "number") {
      if (!this.depthQuantity) {
        this.depthQuantity = new Quantity(depth);
      } else {
        this.depthQuantity.value = depth;
      }
    } else {
      this.depthQuantity = depth;
    }
  }
  get arrivals() {
    return this.arrivalList;
  }
};
var CompositeTime = class _CompositeTime {
  /**
   * Parses a QuakeML composite time xml element into an CompositeTime object.
   *
   * @param qml the composite time xml Element
   * @returns CompositeTime instance
   */
  static createFromXml(qml) {
    if (qml.localName !== "compositeTime") {
      throw new Error(
        `Cannot extract, not a QuakeML Composite Time: ${qml.localName}`
      );
    }
    const out = new _CompositeTime();
    out.year = _grabFirstElIntegerQuantity(qml, "year");
    out.month = _grabFirstElIntegerQuantity(qml, "month");
    out.day = _grabFirstElIntegerQuantity(qml, "day");
    out.hour = _grabFirstElIntegerQuantity(qml, "hour");
    out.minute = _grabFirstElIntegerQuantity(qml, "minute");
    out.second = _grabFirstElIntegerQuantity(qml, "second");
    return out;
  }
};
var OriginUncertainty = class _OriginUncertainty {
  /**
   * Parses a QuakeML origin uncertainty xml element into an OriginUncertainty object.
   *
   * @param qml the origin uncertainty xml Element
   * @returns OriginUncertainty instance
   */
  static createFromXml(qml) {
    if (qml.localName !== "originUncertainty") {
      throw new Error(
        `Cannot extract, not a QuakeML Origin Uncertainty: ${qml.localName}`
      );
    }
    const out = new _OriginUncertainty();
    out.horizontalUncertainty = _grabFirstElFloat3(qml, "horizontalUncertainty");
    out.minHorizontalUncertainty = _grabFirstElFloat3(
      qml,
      "minHorizontalUncertainty"
    );
    out.maxHorizontalUncertainty = _grabFirstElFloat3(
      qml,
      "maxHorizontalUncertainty"
    );
    out.azimuthMaxHorizontalUncertainty = _grabFirstElFloat3(
      qml,
      "azimuthMaxHorizontalUncertainty"
    );
    out.confidenceEllipsoid = _grabFirstElType(
      ConfidenceEllipsoid.createFromXml.bind(ConfidenceEllipsoid)
    )(qml, "confidenceEllipsoid");
    out.preferredDescription = _grabFirstElText3(qml, "preferredDescription");
    out.confidenceLevel = _grabFirstElFloat3(qml, "confidenceLevel");
    return out;
  }
};
var ConfidenceEllipsoid = class _ConfidenceEllipsoid {
  constructor(semiMajorAxisLength, semiMinorAxisLength, semiIntermediateAxisLength, majorAxisPlunge, majorAxisAzimuth, majorAxisRotation) {
    this.semiMajorAxisLength = semiMajorAxisLength;
    this.semiMinorAxisLength = semiMinorAxisLength;
    this.semiIntermediateAxisLength = semiIntermediateAxisLength;
    this.majorAxisPlunge = majorAxisPlunge;
    this.majorAxisAzimuth = majorAxisAzimuth;
    this.majorAxisRotation = majorAxisRotation;
  }
  /**
   * Parses a QuakeML confidence ellipsoid xml element into an ConfidenceEllipsoid object.
   *
   * @param qml the confidence ellipsoid xml Element
   * @returns ConfidenceEllipsoid instance
   */
  static createFromXml(qml) {
    if (qml.localName !== "confidenceEllipsoid") {
      throw new Error(
        `Cannot extract, not a QuakeML Confidence Ellipsoid: ${qml.localName}`
      );
    }
    const semiMajorAxisLength = _grabFirstElFloat3(qml, "semiMajorAxisLength");
    if (semiMajorAxisLength === void 0) {
      throw new Error("confidenceEllipsoid missing semiMajorAxisLength");
    }
    const semiMinorAxisLength = _grabFirstElFloat3(qml, "semiMinorAxisLength");
    if (semiMinorAxisLength === void 0) {
      throw new Error("confidenceEllipsoid missing semiMinorAxisLength");
    }
    const semiIntermediateAxisLength = _grabFirstElFloat3(
      qml,
      "semiIntermediateAxisLength"
    );
    if (semiIntermediateAxisLength === void 0) {
      throw new Error("confidenceEllipsoid missing semiIntermediateAxisLength");
    }
    const majorAxisPlunge = _grabFirstElFloat3(qml, "majorAxisPlunge");
    if (majorAxisPlunge === void 0) {
      throw new Error("confidenceEllipsoid missing majorAxisPlunge");
    }
    const majorAxisAzimuth = _grabFirstElFloat3(qml, "majorAxisAzimuth");
    if (majorAxisAzimuth === void 0) {
      throw new Error("confidenceEllipsoid missing majorAxisAzimuth");
    }
    const majorAxisRotation = _grabFirstElFloat3(qml, "majorAxisRotation");
    if (majorAxisRotation === void 0) {
      throw new Error("confidenceEllipsoid missing majorAxisRotation");
    }
    const out = new _ConfidenceEllipsoid(
      semiMajorAxisLength,
      semiMinorAxisLength,
      semiIntermediateAxisLength,
      majorAxisPlunge,
      majorAxisAzimuth,
      majorAxisRotation
    );
    return out;
  }
};
var OriginQuality = class _OriginQuality {
  /**
   * Parses a QuakeML origin quality xml element into an OriginQuality object.
   *
   * @param qml the origin quality xml Element
   * @returns OriginQuality instance
   */
  static createFromXml(qml) {
    if (qml.localName !== "quality") {
      throw new Error(
        `Cannot extract, not a QuakeML Origin Quality: ${qml.localName}`
      );
    }
    const out = new _OriginQuality();
    out.associatedPhaseCount = _grabFirstElInt3(qml, "associatedPhaseCount");
    out.usedPhaseCount = _grabFirstElInt3(qml, "usedPhaseCount");
    out.associatedStationCount = _grabFirstElInt3(qml, "associatedStationCount");
    out.usedStationCount = _grabFirstElInt3(qml, "usedStationCount");
    out.standardError = _grabFirstElFloat3(qml, "standardError");
    out.azimuthalGap = _grabFirstElFloat3(qml, "azimuthalGap");
    out.secondaryAzimuthalGap = _grabFirstElFloat3(qml, "secondaryAzimuthalGap");
    out.groundTruthLevel = _grabFirstElText3(qml, "groundTruthLevel");
    out.maximumDistance = _grabFirstElFloat3(qml, "maximumDistance");
    out.minimumDistance = _grabFirstElFloat3(qml, "minimumDistance");
    out.medianDistance = _grabFirstElFloat3(qml, "medianDistance");
    return out;
  }
};
var Magnitude = class _Magnitude extends BaseElement {
  constructor(mag, type) {
    super();
    this.stationMagnitudeContributions = [];
    if (typeof mag === "number") {
      this.magQuantity = new Quantity(mag);
    } else {
      this.magQuantity = mag;
    }
    if (type) {
      this.type = type;
    }
  }
  /**
   * Parses a QuakeML magnitude xml element into a Magnitude object.
   *
   * @param qml the magnitude xml Element
   * @param allOrigins origins already extracted from the xml for linking magnitudes with origins
   * @param allStationMagnitudes station magnitudes already extracted from the xml
   * @returns Magnitude instance
   */
  static createFromXml(qml, allOrigins, allStationMagnitudes) {
    if (qml.localName !== "magnitude") {
      throw new Error(
        `Cannot extract, not a QuakeML Magnitude: ${qml.localName}`
      );
    }
    const mag = _grabFirstElRealQuantity(qml, "mag");
    if (!mag) {
      throw new Error("magnitude missing mag");
    }
    const out = new _Magnitude(mag);
    out.populate(qml);
    const stationMagnitudeContributionEls = Array.from(
      qml.getElementsByTagNameNS(BED_NS, "stationMagnitudeContribution")
    );
    out.stationMagnitudeContributions = stationMagnitudeContributionEls.map(
      (smc) => StationMagnitudeContribution.createFromXml(smc, allStationMagnitudes)
    );
    out.type = _grabFirstElText3(qml, "type");
    const originID = _grabFirstElText3(qml, "originID");
    out.origin = allOrigins.find((o) => o.publicId === originID);
    if (originID && !out.origin) {
      throw new Error("No origin with ID " + originID);
    }
    out.methodID = _grabFirstElText3(qml, "methodID");
    out.stationCount = _grabFirstElInt3(qml, "stationCount");
    out.azimuthalGap = _grabFirstElFloat3(qml, "azimuthalGap");
    out.evaluationMode = _grabFirstElText3(qml, "evaluationMode");
    out.evaluationStatus = _grabFirstElText3(qml, "evaluationStatus");
    return out;
  }
  toString() {
    return `${magFormat.format(this.mag)} ${this.type ? this.type : ""}`;
  }
  get mag() {
    return this.magQuantity.value;
  }
  set mag(value) {
    if (typeof value === "number") {
      this.magQuantity.value = value;
    } else {
      this.magQuantity = value;
    }
  }
};
var StationMagnitudeContribution = class _StationMagnitudeContribution {
  constructor(stationMagnitude) {
    this.stationMagnitude = stationMagnitude;
  }
  /**
   * Parses a QuakeML station magnitude contribution xml element into a StationMagnitudeContribution object.
   *
   * @param qml the station magnitude contribution xml Element
   * @param allStationMagnitudes station magnitudes already extracted from the xml for linking station magnitudes with station magnitude contributions
   * @returns StationMagnitudeContribution instance
   */
  static createFromXml(qml, allStationMagnitudes) {
    if (qml.localName !== "stationMagnitudeContribution") {
      throw new Error(
        `Cannot extract, not a QuakeML StationMagnitudeContribution: ${qml.localName}`
      );
    }
    const stationMagnitudeID = _grabFirstElText3(qml, "stationMagnitudeID");
    if (!isNonEmptyStringArg(stationMagnitudeID)) {
      throw new Error("stationMagnitudeContribution missing stationMagnitude");
    }
    const stationMagnitude = allStationMagnitudes.find(
      (sm) => sm.publicId === stationMagnitudeID
    );
    if (!isDef(stationMagnitude)) {
      throw new Error("No stationMagnitude with ID " + stationMagnitudeID);
    }
    const out = new _StationMagnitudeContribution(stationMagnitude);
    out.residual = _grabFirstElFloat3(qml, "residual");
    out.weight = _grabFirstElFloat3(qml, "weight");
    return out;
  }
};
var Arrival = class _Arrival extends BaseElement {
  constructor(phase, pick3) {
    super();
    this.phase = phase;
    this.pick = pick3;
  }
  /**
   * Parses a QuakeML arrival xml element into a Arrival object.
   *
   * @param arrivalQML the arrival xml Element
   * @param allPicks picks already extracted from the xml for linking arrivals with picks
   * @returns Arrival instance
   */
  static createFromXml(arrivalQML, allPicks) {
    if (arrivalQML.localName !== "arrival") {
      throw new Error(
        `Cannot extract, not a QuakeML Arrival: ${arrivalQML.localName}`
      );
    }
    const pickId = _grabFirstElText3(arrivalQML, "pickID");
    const phase = _grabFirstElText3(arrivalQML, "phase");
    if (isNonEmptyStringArg(phase) && isNonEmptyStringArg(pickId)) {
      const myPick = allPicks.find(function(p) {
        return p.publicId === pickId;
      });
      if (!myPick) {
        throw new Error("Can't find pick with Id=" + pickId + " for Arrival");
      }
      const out = new _Arrival(phase, myPick);
      out.populate(arrivalQML);
      out.timeCorrection = _grabFirstElFloat3(arrivalQML, "timeCorrection");
      out.azimuth = _grabFirstElFloat3(arrivalQML, "azimuth");
      out.distance = _grabFirstElFloat3(arrivalQML, "distance");
      out.takeoffAngle = _grabFirstElRealQuantity(arrivalQML, "takeoffAngle");
      out.timeResidual = _grabFirstElFloat3(arrivalQML, "timeResidual");
      out.horizontalSlownessResidual = _grabFirstElFloat3(
        arrivalQML,
        "horizontalSlownessResidual"
      );
      out.backazimuthResidual = _grabFirstElFloat3(
        arrivalQML,
        "backazimuthResidual"
      );
      out.timeWeight = _grabFirstElFloat3(arrivalQML, "timeWeight");
      out.horizontalSlownessWeight = _grabFirstElFloat3(
        arrivalQML,
        "horizontalSlownessWeight"
      );
      out.backazimuthWeight = _grabFirstElFloat3(
        arrivalQML,
        "backazimuthWeight"
      );
      out.earthModelID = _grabFirstElText3(arrivalQML, "earthModelID");
      return out;
    } else {
      throw new Error(
        "Arrival does not have phase or pickId: " + stringify(phase) + " " + stringify(pickId)
      );
    }
  }
};
var Pick = class _Pick extends BaseElement {
  constructor(time3, waveformID) {
    super();
    if (time3 instanceof DateTime) {
      this.timeQuantity = new Quantity(time3);
    } else {
      this.timeQuantity = time3;
    }
    this.waveformID = waveformID;
  }
  get time() {
    return this.timeQuantity.value;
  }
  set time(t) {
    if (t instanceof DateTime) {
      this.timeQuantity.value = t;
    } else {
      this.timeQuantity = t;
    }
  }
  /**
   * Parses a QuakeML pick xml element into a Pick object.
   *
   * @param pickQML the pick xml Element
   * @returns Pick instance
   */
  static createFromXml(pickQML) {
    if (pickQML.localName !== "pick") {
      throw new Error(
        `Cannot extract, not a QuakeML Pick: ${pickQML.localName}`
      );
    }
    const time3 = _grabFirstElTimeQuantity(pickQML, "time");
    if (!isDef(time3)) {
      throw new Error("Missing time");
    }
    const waveformId = _grabFirstElType(
      WaveformID.createFromXml.bind(WaveformID)
    )(pickQML, "waveformID");
    if (!isObject(waveformId)) {
      throw new Error("pick missing waveformID");
    }
    const out = new _Pick(time3, waveformId);
    out.populate(pickQML);
    out.filterID = _grabFirstElText3(pickQML, "filterID");
    out.methodID = _grabFirstElText3(pickQML, "methodID");
    out.horizontalSlowness = _grabFirstElRealQuantity(
      pickQML,
      "horizontalSlowness"
    );
    out.backazimuth = _grabFirstElRealQuantity(pickQML, "backazimuth");
    out.slownessMethodID = _grabFirstElText3(pickQML, "slownessMethodID");
    out.onset = _grabFirstElText3(pickQML, "onset");
    out.phaseHint = _grabFirstElText3(pickQML, "phaseHint");
    out.polarity = _grabFirstElText3(pickQML, "polarity");
    out.evaluationMode = _grabFirstElText3(pickQML, "evaluationMode");
    out.evaluationStatus = _grabFirstElText3(pickQML, "evaluationStatus");
    return out;
  }
  get networkCode() {
    return this.waveformID.networkCode;
  }
  get stationCode() {
    return this.waveformID.stationCode;
  }
  get locationCode() {
    return this.waveformID.locationCode || "--";
  }
  get channelCode() {
    return this.waveformID.channelCode || "---";
  }
  isAtStation(station) {
    return this.networkCode === station.networkCode && this.stationCode === station.stationCode;
  }
  isOnChannel(channel) {
    return this.networkCode === channel.station.networkCode && this.stationCode === channel.station.stationCode && this.locationCode === channel.locationCode && this.channelCode === channel.channelCode;
  }
  toString() {
    return stringify(this.time) + ` ${this.networkCode}.${this.stationCode}.${this.locationCode}.${this.channelCode}`;
  }
};
var FocalMechanism = class _FocalMechanism extends BaseElement {
  constructor() {
    super(...arguments);
    this.waveformIDList = [];
    this.momentTensorList = [];
  }
  /**
   * Parses a QuakeML focal mechanism xml element into a FocalMechanism object.
   *
   * @param focalMechQML the focal mechanism xml Element
   * @param allOrigins origins already extracted from the xml for linking focal mechanisms with origins
   * @param allMagnitudes magnitudes already extracted from the xml for linking moment tensors with magnitudes
   * @returns FocalMechanism instance
   */
  static createFromXml(focalMechQML, allOrigins, allMagnitudes) {
    if (focalMechQML.localName !== "focalMechanism") {
      throw new Error(
        `Cannot extract, not a QuakeML focalMechanism: ${focalMechQML.localName}`
      );
    }
    const out = new _FocalMechanism();
    out.populate(focalMechQML);
    const waveformIDEls = Array.from(
      focalMechQML.getElementsByTagNameNS(BED_NS, "waveformID")
    );
    out.waveformIDList = waveformIDEls.map(
      (wid) => WaveformID.createFromXml(wid)
    );
    const momentTensorEls = Array.from(
      focalMechQML.getElementsByTagNameNS(BED_NS, "momentTensor")
    );
    out.momentTensorList = momentTensorEls.map(
      (mt) => MomentTensor.createFromXml(mt, allOrigins, allMagnitudes)
    );
    const triggeringOriginID = _grabFirstElText3(
      focalMechQML,
      "triggeringOriginID"
    );
    out.triggeringOrigin = allOrigins.find(
      (o) => o.publicId === triggeringOriginID
    );
    if (triggeringOriginID && !out.triggeringOrigin) {
      throw new Error("No origin with ID " + triggeringOriginID);
    }
    out.nodalPlanes = _grabFirstElType(
      NodalPlanes.createFromXml.bind(NodalPlanes)
    )(focalMechQML, "nodalPlanes");
    out.principalAxes = _grabFirstElType(
      PrincipalAxes.createFromXml.bind(PrincipalAxes)
    )(focalMechQML, "principalAxes");
    out.azimuthalGap = _grabFirstElFloat3(focalMechQML, "azimuthalGap");
    out.stationPolarityCount = _grabFirstElInt3(
      focalMechQML,
      "stationPolarityCount"
    );
    out.misfit = _grabFirstElFloat3(focalMechQML, "misfit");
    out.stationDistributionRatio = _grabFirstElFloat3(
      focalMechQML,
      "stationDistributionRatio"
    );
    out.methodID = _grabFirstElText3(focalMechQML, "methodID");
    out.evaluationMode = _grabFirstElText3(focalMechQML, "evaluationMode");
    out.evaluationStatus = _grabFirstElText3(focalMechQML, "evaluationStatus");
    return out;
  }
};
var NodalPlanes = class _NodalPlanes {
  /**
   * Parses a QuakeML nodal planes xml element into a NodalPlanes object.
   *
   * @param nodalPlanesQML the nodal planes xml Element
   * @returns NodalPlanes instance
   */
  static createFromXml(nodalPlanesQML) {
    const out = new _NodalPlanes();
    out.nodalPlane1 = _grabFirstElType(
      NodalPlane.createFromXml.bind(NodalPlane)
    )(nodalPlanesQML, "nodalPlane1");
    out.nodalPlane2 = _grabFirstElType(
      NodalPlane.createFromXml.bind(NodalPlane)
    )(nodalPlanesQML, "nodalPlane2");
    const preferredPlaneString = _grabAttribute3(
      nodalPlanesQML,
      "preferredPlane"
    );
    out.preferredPlane = isNonEmptyStringArg(preferredPlaneString) ? parseInt(preferredPlaneString) : void 0;
    return out;
  }
};
var NodalPlane = class _NodalPlane {
  constructor(strike, dip, rake) {
    this.strike = strike;
    this.dip = dip;
    this.rake = rake;
  }
  /**
   * Parses a QuakeML nodal plane xml element into a NodalPlane object.
   *
   * @param nodalPlaneQML the nodal plane xml Element
   * @returns NodalPlane instance
   */
  static createFromXml(nodalPlaneQML) {
    const strike = _grabFirstElRealQuantity(nodalPlaneQML, "strike");
    if (!isObject(strike)) {
      throw new Error("nodal plane missing strike");
    }
    const dip = _grabFirstElRealQuantity(nodalPlaneQML, "dip");
    if (!isObject(dip)) {
      throw new Error("nodal plane missing dip");
    }
    const rake = _grabFirstElRealQuantity(nodalPlaneQML, "rake");
    if (!isObject(rake)) {
      throw new Error("nodal plane missing rake");
    }
    const out = new _NodalPlane(strike, dip, rake);
    return out;
  }
};
var PrincipalAxes = class _PrincipalAxes {
  constructor(tAxis, pAxis) {
    this.tAxis = tAxis;
    this.pAxis = pAxis;
  }
  /**
   * Parses a QuakeML princpalAxes element into a PrincipalAxes object.
   *
   * @param princpalAxesQML the princpalAxes xml Element
   * @returns PrincipalAxes instance
   */
  static createFromXml(princpalAxesQML) {
    if (princpalAxesQML.localName !== "principalAxes") {
      throw new Error(
        `Cannot extract, not a QuakeML princpalAxes: ${princpalAxesQML.localName}`
      );
    }
    const tAxis = _grabFirstElType(Axis.createFromXml.bind(Axis))(
      princpalAxesQML,
      "tAxis"
    );
    if (!isObject(tAxis)) {
      throw new Error("nodal plane missing tAxis");
    }
    const pAxis = _grabFirstElType(Axis.createFromXml.bind(Axis))(
      princpalAxesQML,
      "pAxis"
    );
    if (!isObject(pAxis)) {
      throw new Error("nodal plane missing pAxis");
    }
    const out = new _PrincipalAxes(tAxis, pAxis);
    out.nAxis = _grabFirstElType(Axis.createFromXml.bind(Axis))(
      princpalAxesQML,
      "nAxis"
    );
    return out;
  }
};
var Axis = class _Axis {
  constructor(azimuth, plunge, length) {
    this.azimuth = azimuth;
    this.plunge = plunge;
    this.length = length;
  }
  /**
   * Parses a QuakeML axis xml element into a Axis object.
   *
   * @param axisQML the axis xml Element
   * @returns Axis instance
   */
  static createFromXml(axisQML) {
    const azimuth = _grabFirstElRealQuantity(axisQML, "azimuth");
    if (!isObject(azimuth)) {
      throw new Error("nodal plane missing azimuth");
    }
    const plunge = _grabFirstElRealQuantity(axisQML, "plunge");
    if (!isObject(plunge)) {
      throw new Error("nodal plane missing plunge");
    }
    const length = _grabFirstElRealQuantity(axisQML, "length");
    if (!isObject(length)) {
      throw new Error("nodal plane missing length");
    }
    const out = new _Axis(azimuth, plunge, length);
    return out;
  }
};
var MomentTensor = class _MomentTensor extends BaseElement {
  constructor(derivedOrigin) {
    super();
    this.dataUsedList = [];
    this.derivedOrigin = derivedOrigin;
  }
  /**
   * Parses a QuakeML momentTensor xml element into a MomentTensor object.
   *
   * @param momentTensorQML the momentTensor xml Element
   * @param allOrigins origins already extracted from the xml for linking moment tensors with origins
   * @param allMagnitudes magnitudes already extracted from the xml for linking moment tensors with magnitudes
   * @returns MomentTensor instance
   */
  static createFromXml(momentTensorQML, allOrigins, allMagnitudes) {
    if (momentTensorQML.localName !== "momentTensor") {
      throw new Error(
        `Cannot extract, not a QuakeML momentTensor: ${momentTensorQML.localName}`
      );
    }
    const derivedOriginID = _grabFirstElText3(
      momentTensorQML,
      "derivedOriginID"
    );
    let derivedOrigin;
    if (!isNonEmptyStringArg(derivedOriginID)) {
      console.warn("momentTensor missing derivedOriginID");
    } else {
      derivedOrigin = allOrigins.find(
        (o) => o.publicId === derivedOriginID
      );
      if (!isDef(derivedOrigin)) {
        throw new Error("No origin with ID " + derivedOriginID);
      }
    }
    const out = new _MomentTensor(derivedOrigin);
    out.populate(momentTensorQML);
    const dataUsedEls = Array.from(
      momentTensorQML.getElementsByTagNameNS(BED_NS, "dataUsed")
    );
    out.dataUsedList = dataUsedEls.map(DataUsed.createFromXml.bind(DataUsed));
    const momentMagnitudeID = _grabFirstElText3(
      momentTensorQML,
      "momentMagnitudeID"
    );
    out.momentMagnitude = allMagnitudes.find(
      (o) => o.publicId === momentMagnitudeID
    );
    if (momentMagnitudeID && !out.momentMagnitude) {
      throw new Error("No magnitude with ID " + momentMagnitudeID);
    }
    try {
      out.scalarMoment = _grabFirstElRealQuantity(
        momentTensorQML,
        "scalarMoment"
      );
    } catch {
      const scalMom = _grabFirstElFloat3(momentTensorQML, "scalarMoment");
      if (scalMom != null) {
        out.scalarMoment = new Quantity(scalMom);
      } else {
        warn(`scalarMoment in momentTensor is invalid: ${_grabFirstEl2(momentTensorQML, "scalarMoment")}`);
      }
      warn(`scalarMoment in momentTensor is invalid: ${_grabFirstEl2(momentTensorQML, "scalarMoment")}`);
    }
    out.tensor = _grabFirstElType(Tensor.createFromXml.bind(Tensor))(
      momentTensorQML,
      "tensor"
    );
    out.variance = _grabFirstElFloat3(momentTensorQML, "variance");
    out.varianceReduction = _grabFirstElFloat3(
      momentTensorQML,
      "varianceReduction"
    );
    out.doubleCouple = _grabFirstElFloat3(momentTensorQML, "doubleCouple");
    out.clvd = _grabFirstElFloat3(momentTensorQML, "clvd");
    out.iso = _grabFirstElFloat3(momentTensorQML, "iso");
    out.greensFunctionID = _grabFirstElText3(
      momentTensorQML,
      "greensFunctionID"
    );
    out.filterID = _grabFirstElText3(momentTensorQML, "filterID");
    out.sourceTimeFunction = _grabFirstElType(
      SourceTimeFunction.createFromXml.bind(SourceTimeFunction)
    )(momentTensorQML, "sourceTimeFunction");
    out.methodID = _grabFirstElText3(momentTensorQML, "methodID");
    out.category = _grabFirstElText3(momentTensorQML, "category");
    out.inversionType = _grabFirstElText3(momentTensorQML, "inversionType");
    return out;
  }
};
var Tensor = class _Tensor {
  constructor(Mrr, Mtt, Mpp, Mrt, Mrp, Mtp) {
    this.Mrr = Mrr;
    this.Mtt = Mtt;
    this.Mpp = Mpp;
    this.Mrt = Mrt;
    this.Mrp = Mrp;
    this.Mtp = Mtp;
  }
  /**
   * Parses a QuakeML tensor xml element into a Tensor object.
   *
   * @param tensorQML the tensor xml Element
   * @returns Tensor instance
   */
  static createFromXml(tensorQML) {
    if (tensorQML.localName !== "tensor") {
      throw new Error(
        `Cannot extract, not a QuakeML tensor: ${tensorQML.localName}`
      );
    }
    const Mrr = _grabFirstElRealQuantity(tensorQML, "Mrr");
    if (!isObject(Mrr)) {
      throw new Error("tensor missing Mrr");
    }
    const Mtt = _grabFirstElRealQuantity(tensorQML, "Mtt");
    if (!isObject(Mtt)) {
      throw new Error("tensor missing Mtt");
    }
    const Mpp = _grabFirstElRealQuantity(tensorQML, "Mpp");
    if (!isObject(Mpp)) {
      throw new Error("tensor missing Mpp");
    }
    const Mrt = _grabFirstElRealQuantity(tensorQML, "Mrt");
    if (!isObject(Mrt)) {
      throw new Error("tensor missing Mrt");
    }
    const Mrp = _grabFirstElRealQuantity(tensorQML, "Mrp");
    if (!isObject(Mrp)) {
      throw new Error("tensor missing Mrp");
    }
    const Mtp = _grabFirstElRealQuantity(tensorQML, "Mtp");
    if (!isObject(Mtp)) {
      throw new Error("tensor missing Mtp");
    }
    const out = new _Tensor(Mrr, Mtt, Mpp, Mrt, Mrp, Mtp);
    return out;
  }
};
var SourceTimeFunction = class _SourceTimeFunction {
  constructor(type, duration3) {
    this.type = type;
    this.duration = duration3;
  }
  /**
   * Parses a QuakeML sourceTimeFunction xml element into a SourceTimeFunction object.
   *
   * @param sourceTimeFunctionQML the sourceTimeFunction xml Element
   * @returns SourceTimeFunction instance
   */
  static createFromXml(sourceTimeFunctionQML) {
    if (sourceTimeFunctionQML.localName !== "sourceTimeFunction") {
      throw new Error(
        `Cannot extract, not a QuakeML sourceTimeFunction: ${sourceTimeFunctionQML.localName}`
      );
    }
    const type = _grabFirstElText3(sourceTimeFunctionQML, "type");
    if (!isNonEmptyStringArg(type)) {
      throw new Error("sourceTimeFunction missing type");
    }
    const duration3 = _grabFirstElFloat3(sourceTimeFunctionQML, "duration");
    if (!isDef(duration3)) {
      throw new Error("sourceTimeFunction missing duration");
    }
    const out = new _SourceTimeFunction(type, duration3);
    out.riseTime = _grabFirstElFloat3(sourceTimeFunctionQML, "riseTime");
    out.decayTime = _grabFirstElFloat3(sourceTimeFunctionQML, "decayTime");
    return out;
  }
};
var DataUsed = class _DataUsed {
  constructor(waveType) {
    this.waveType = waveType;
  }
  /**
   * Parses a QuakeML dataUsed xml element into a DataUsed object.
   *
   * @param dataUsedQML the dataUsed xml Element
   * @returns SourceTimeFunction instance
   */
  static createFromXml(dataUsedQML) {
    if (dataUsedQML.localName !== "dataUsed") {
      throw new Error(
        `Cannot extract, not a QuakeML dataUsed: ${dataUsedQML.localName}`
      );
    }
    const waveType = _grabFirstElText3(dataUsedQML, "waveType");
    if (!isNonEmptyStringArg(waveType)) {
      throw new Error("dataUsed missing waveType");
    }
    const out = new _DataUsed(waveType);
    out.stationCount = _grabFirstElInt3(dataUsedQML, "stationCount");
    out.componentCount = _grabFirstElInt3(dataUsedQML, "componentCount");
    out.shortestPeriod = _grabFirstElFloat3(dataUsedQML, "shortestPeriod");
    out.longestPeriod = _grabFirstElFloat3(dataUsedQML, "longestPeriod");
    return out;
  }
};
var WaveformID = class _WaveformID {
  constructor(networkCode, stationCode) {
    this.networkCode = networkCode;
    this.stationCode = stationCode;
  }
  /**
   * Parses a QuakeML waveform ID xml element into a WaveformID object.
   *
   * @param waveformQML the waveform ID xml Element
   * @returns WaveformID instance
   */
  static createFromXml(waveformQML) {
    if (waveformQML.localName !== "waveformID") {
      throw new Error(
        `Cannot extract, not a QuakeML waveform ID: ${waveformQML.localName}`
      );
    }
    const networkCode = _grabAttribute3(waveformQML, "networkCode");
    if (!isNonEmptyStringArg(networkCode)) {
      throw new Error("waveformID missing networkCode");
    }
    const stationCode = _grabAttribute3(waveformQML, "stationCode");
    if (!isNonEmptyStringArg(stationCode)) {
      throw new Error("waveformID missing stationCode");
    }
    const out = new _WaveformID(networkCode, stationCode);
    out.channelCode = _grabAttribute3(waveformQML, "channelCode");
    out.locationCode = _grabAttribute3(waveformQML, "locationCode");
    return out;
  }
  toString() {
    return `${this.networkCode}.${this.stationCode}.${this.locationCode || "--"}.${this.channelCode || "---"}`;
  }
};
var Quantity = class _Quantity {
  constructor(value) {
    this.value = value;
  }
  /**
   * Parses a QuakeML quantity xml element into a Quantity object.
   *
   * @param quantityQML the quantity xml Element
   * @param grab a callback to obtain the value
   * @param grabUncertainty a callback to obtain the uncertainties
   * @returns Quantity instance
   */
  static _createFromXml(quantityQML, grab, grabUncertainty) {
    const value = grab(quantityQML, "value");
    if (value === void 0) {
      throw new Error("missing value");
    }
    const out = new _Quantity(value);
    out.uncertainty = grabUncertainty(quantityQML, "uncertainty");
    out.lowerUncertainty = grabUncertainty(quantityQML, "lowerUncertainty");
    out.upperUncertainty = grabUncertainty(quantityQML, "upperUncertainty");
    out.confidenceLevel = _grabFirstElFloat3(quantityQML, "confidenceLevel");
    return out;
  }
  /**
   * Parses a QuakeML real quantity xml element into a RealQuantity object.
   *
   * @param realQuantityQML the real quantity xml Element
   * @returns RealQuantity instance
   */
  static createRealQuantityFromXml(realQuantityQML) {
    return _Quantity._createFromXml(
      realQuantityQML,
      _grabFirstElFloat3,
      _grabFirstElFloat3
    );
  }
  /**
   * Parses a QuakeML integer quantity xml element into a RealQuantity object.
   *
   * @param integerQuantityQML the integer quantity xml Element
   * @returns IntegerQuantity instance
   */
  static createIntegerQuantityFromXml(integerQuantityQML) {
    return _Quantity._createFromXml(
      integerQuantityQML,
      _grabFirstElFloat3,
      _grabFirstElInt3
    );
  }
  /**
   * Parses a QuakeML time quantity xml element into a TimeQuantity object.
   *
   * @param timeQuantityQML the time quantity xml Element
   * @returns TimeQuantity instance
   */
  static createTimeQuantityFromXml(timeQuantityQML) {
    return _Quantity._createFromXml(
      timeQuantityQML,
      _grabFirstElDateTime,
      _grabFirstElFloat3
    );
  }
};
var Comment2 = class _Comment {
  constructor(text) {
    this.text = text;
  }
  /**
   * Parses a QuakeML comment xml element into a Comment object.
   *
   * @param commentQML the comment xml Element
   * @returns Comment instance
   */
  static createFromXml(commentQML) {
    const text = _grabFirstElText3(commentQML, "text");
    if (text === void 0) {
      throw new Error("missing value");
    }
    const out = new _Comment(text);
    out.creationInfo = _grabFirstElCreationInfo(commentQML, "creationInfo");
    return out;
  }
};
var CreationInfo = class _CreationInfo {
  /**
   * Parses a QuakeML creation info xml element into a CreationInfo object.
   *
   * @param creationInfoQML the creation info xml Element
   * @returns CreationInfo instance
   */
  static createFromXml(creationInfoQML) {
    const out = new _CreationInfo();
    out.agencyID = _grabFirstElText3(creationInfoQML, "agencyID");
    out.agencyURI = _grabFirstElText3(creationInfoQML, "agencyURI");
    out.author = _grabFirstElText3(creationInfoQML, "author");
    out.authorURI = _grabFirstElText3(creationInfoQML, "authorURI");
    out.creationTime = _grabFirstElDateTime(creationInfoQML, "creationTime");
    out.version = _grabFirstElText3(creationInfoQML, "version");
    return out;
  }
};
function parseQuakeML(rawXml, host) {
  const top2 = rawXml.documentElement;
  if (!top2) {
    throw new Error("Can't get documentElement");
  }
  const eventParametersArray = Array.from(
    top2.getElementsByTagName("eventParameters")
  );
  if (eventParametersArray.length !== 1) {
    throw new Error(
      `Document has ${eventParametersArray.length} eventParameters elements`
    );
  }
  return EventParameters.createFromXml(eventParametersArray[0], host);
}
function createQuakeFromValues(publicId, time3, latitude, longitude, depth_meter) {
  const origin = new Origin(
    new Quantity(time3),
    new Quantity(latitude),
    new Quantity(longitude)
  );
  origin.depth = new Quantity(depth_meter);
  const quake = new Quake();
  quake.publicId = publicId;
  quake.originList.push(origin);
  quake.preferredOrigin = origin;
  return quake;
}
function fetchQuakeML(url2, timeoutSec2 = 10, nodata = 204) {
  const fetchInit = defaultFetchInitObj(XML_MIME);
  const host = new URL(url2).hostname;
  return doFetchWithTimeout(url2, fetchInit, timeoutSec2 * 1e3).then((response) => {
    if (response.status === 200) {
      return response.text();
    } else if (response.status === 204 || isDef(nodata) && response.status === nodata) {
      return FAKE_EMPTY_XML2;
    } else {
      throw new Error(`Status not successful: ${response.status}`);
    }
  }).then(function(rawXmlText) {
    return new DOMParser().parseFromString(rawXmlText, XML_MIME);
  }).then((rawXml) => {
    return parseQuakeML(rawXml, host);
  });
}
function mightBeQuakeML(buf) {
  if (!mightBeXml(buf)) {
    return false;
  }
  const initialChars = dataViewToString(new DataView(buf.slice(0, 100))).trimStart();
  if (!initialChars.includes("quakeml")) {
    return false;
  }
  return true;
}
function createUnknownId() {
  const max = 1e6;
  let s2 = `${Math.floor(Math.random() * max)}`;
  s2 = s2.padStart(6, "0");
  return `${UNKNOWN_PUBLIC_ID}_${s2}`;
}
var ZERO_MAGNITUDE = new Magnitude(new Quantity(0), "unk");
var _grabAllElComment = function(xml, tagName) {
  const out = [];
  if (isObject(xml)) {
    const elList = Array.from(xml.children).filter(
      (e) => e.tagName === tagName
    );
    for (const el of elList) {
      if (isObject(el)) {
        out.push(Comment2.createFromXml(el));
      }
    }
  }
  return out;
};
var _grabFirstElNS = function(xml, namespace, tagName) {
  let out = null;
  if (isObject(xml)) {
    const elList = xml.getElementsByTagNameNS(namespace, tagName);
    for (let idx = 0; idx < elList.length; idx++) {
      const e = elList.item(idx);
      if (e != null && e.parentElement === xml) {
        if (e) {
          out = e;
          break;
        }
      }
    }
  }
  return out;
};
var _grabFirstEl2 = function(xml, tagName) {
  if (isObject(xml)) {
    const elList = Array.from(xml.children).filter(
      (e) => e.tagName === tagName
    );
    if (elList.length > 0) {
      const e = elList[0];
      if (e) {
        return e;
      }
    }
  }
  return void 0;
};
var _grabFirstElText3 = function(xml, tagName) {
  let out = void 0;
  const el = _grabFirstEl2(xml, tagName);
  if (isObject(el)) {
    out = el.textContent;
    if (out === null) {
      out = void 0;
    }
  }
  return out;
};
var _grabFirstElBool = function(xml, tagName) {
  const el = _grabFirstElText3(xml, tagName);
  if (!isStringArg(el)) {
    return void 0;
  }
  switch (el) {
    case "true":
    case "1":
      return true;
    case "false":
    case "0":
      return false;
  }
  throw new Error("Invalid boolean: " + el);
};
var _grabFirstElInt3 = function(xml, tagName) {
  let out = void 0;
  const el = _grabFirstElText3(xml, tagName);
  if (isStringArg(el)) {
    out = parseInt(el);
  }
  return out;
};
var _grabFirstElFloat3 = function(xml, tagName) {
  let out = void 0;
  const el = _grabFirstElText3(xml, tagName);
  if (isStringArg(el)) {
    out = parseFloat(el);
  }
  return out;
};
var _grabFirstElDateTime = function(xml, tagName) {
  let out = void 0;
  const el = _grabFirstElText3(xml, tagName);
  if (isStringArg(el)) {
    out = isoToDateTime(el);
  }
  return out;
};
var _grabFirstElType = function(createFromXml) {
  return function(xml, tagName) {
    let out = void 0;
    const el = _grabFirstEl2(xml, tagName);
    if (isObject(el)) {
      out = createFromXml(el);
    }
    return out;
  };
};
var _grabFirstElRealQuantity = _grabFirstElType(
  Quantity.createRealQuantityFromXml.bind(Quantity)
);
var _grabFirstElIntegerQuantity = _grabFirstElType(
  Quantity.createIntegerQuantityFromXml.bind(Quantity)
);
var _grabFirstElTimeQuantity = _grabFirstElType(
  Quantity.createTimeQuantityFromXml.bind(Quantity)
);
var _grabFirstElCreationInfo = _grabFirstElType(
  CreationInfo.createFromXml.bind(CreationInfo)
);
var _grabAttribute3 = function(xml, tagName) {
  let out = void 0;
  if (isObject(xml)) {
    const a = xml.getAttribute(tagName);
    if (isStringArg(a)) {
      out = a;
    }
  }
  return out;
};
var _requireAttribute3 = function _requireAttribute4(xml, tagName) {
  const out = _grabAttribute3(xml, tagName);
  if (typeof out !== "string") {
    throw new Error(`Attribute ${tagName} not found.`);
  }
  return out;
};
var _grabAttributeNS2 = function(xml, namespace, tagName) {
  let out = void 0;
  if (isObject(xml)) {
    const a = xml.getAttributeNS(namespace, tagName);
    if (isStringArg(a)) {
      out = a;
    }
  }
  return out;
};
var parseUtil2 = {
  _grabFirstEl: _grabFirstEl2,
  _grabFirstElNS,
  _grabFirstElText: _grabFirstElText3,
  _grabFirstElFloat: _grabFirstElFloat3,
  _grabFirstElInt: _grabFirstElInt3,
  _grabAttribute: _grabAttribute3,
  _requireAttribute: _requireAttribute3,
  _grabAttributeNS: _grabAttributeNS2
};

// src/seismogram.mts
var COUNT_UNIT2 = "count";
var Seismogram = class _Seismogram {
  constructor(segmentArray) {
    this._y = null;
    if (Array.isArray(segmentArray) && segmentArray[0] instanceof SeismogramSegment) {
      this._segmentArray = segmentArray;
    } else if (segmentArray instanceof SeismogramSegment) {
      this._segmentArray = [segmentArray];
    } else {
      throw new Error(
        `segmentArray is not Array<SeismogramSegment> or SeismogramSegment: ${stringify(
          segmentArray
        )}`
      );
    }
    this.checkAllSimilar();
    this._interval = this.findStartEnd();
    checkLuxonValid(this._interval, "seis const");
  }
  checkAllSimilar() {
    if (this._segmentArray.length === 0) {
      throw new Error("Seismogram is empty");
    }
    const f = this._segmentArray[0];
    this._segmentArray.forEach((s2, i) => {
      if (!s2) {
        throw new Error(`index ${i} is null in trace`);
      }
      this.checkSimilar(f, s2);
    });
  }
  checkSimilar(f, s2) {
    if (!s2.sourceId.equals(f.sourceId)) {
      throw new Error(
        `SourceId not same: ${s2.sourceId.toString()} !== ${f.sourceId.toString()}`
      );
    }
    if (s2.yUnit !== f.yUnit) {
      throw new Error("yUnit not same: " + s2.yUnit + " !== " + f.yUnit);
    }
  }
  findStartEnd() {
    if (this._segmentArray.length === 0) {
      throw new Error("Seismogram is empty");
    }
    return this._segmentArray.reduce(
      (acc, cur) => acc.union(cur.timeRange),
      this._segmentArray[0].timeRange
    );
  }
  findMinMax(minMaxAccumulator) {
    if (this._segmentArray.length === 0) {
      throw new Error("No data");
    }
    for (const s2 of this._segmentArray) {
      minMaxAccumulator = s2.findMinMax(minMaxAccumulator);
    }
    if (minMaxAccumulator) {
      return minMaxAccumulator;
    } else {
      throw new Error("No data to calc minmax");
    }
  }
  /**
   * calculates the mean of a seismogrma.
   *
   * @returns       mean value
   */
  mean() {
    let meanVal = 0;
    const npts = this.numPoints;
    for (const s2 of this.segments) {
      meanVal += meanOfSlice(s2.y, s2.y.length) * s2.numPoints;
    }
    meanVal = meanVal / npts;
    return meanVal;
  }
  get start() {
    return this.startTime;
  }
  get startTime() {
    return validStartTime(this._interval);
  }
  get end() {
    return this.endTime;
  }
  get endTime() {
    return validEndTime(this._interval);
  }
  get timeRange() {
    return this._interval;
  }
  get networkCode() {
    return this.sourceId.networkCode;
  }
  get stationCode() {
    return this.sourceId.stationCode;
  }
  get locationCode() {
    return this.sourceId.locationCode;
  }
  get channelCode() {
    return this.sourceId.formChannelCode();
  }
  /**
   * return FDSN source id as a string.
   *
   * @returns FDSN source id
   */
  get sourceId() {
    return this._segmentArray[0].sourceId;
  }
  set sourceId(sid) {
    this._segmentArray.forEach((s2) => s2.sourceId = sid);
  }
  get sampleRate() {
    return this._segmentArray[0].sampleRate;
  }
  get samplePeriod() {
    return 1 / this.sampleRate;
  }
  get yUnit() {
    return this._segmentArray[0].yUnit;
  }
  isYUnitCount() {
    return this.yUnit?.toLowerCase() === COUNT_UNIT2;
  }
  get numPoints() {
    return this._segmentArray.reduce(
      (accumulator, seis) => accumulator + seis.numPoints,
      0
    );
  }
  hasCodes() {
    return this._segmentArray[0].hasCodes();
  }
  /**
   * return network, station, location and channels codes as one string.
   * Uses this.channel if it exists, this.seismogram if not.
   *
   * @returns net.sta.loc.chan
   */
  get nslc() {
    return this.codes();
  }
  get nslcId() {
    return this._segmentArray[0].nslcId;
  }
  codes() {
    return this._segmentArray[0].codes();
  }
  get segments() {
    return this._segmentArray;
  }
  append(seismogram) {
    if (seismogram instanceof _Seismogram) {
      seismogram._segmentArray.forEach((s2) => this.append(s2));
    } else {
      this.checkSimilar(this._segmentArray[0], seismogram);
      this._interval = this._interval.union(seismogram.timeRange);
      this._segmentArray.push(seismogram);
    }
  }
  /**
   * Cut the seismogram. Creates a new seismogram with all datapoints
   * contained in the time window.
   *
   * @param  timeRange start and end of cut
   * @returns            new seismogram
   */
  cut(timeRange) {
    let out = this.trim(timeRange);
    if (out && out._segmentArray) {
      const cutSeisArray = this._segmentArray.map((seg) => seg.cut(timeRange)).filter(isDef);
      if (cutSeisArray.length > 0) {
        out = new _Seismogram(cutSeisArray);
      } else {
        out = null;
      }
    } else {
      out = null;
    }
    return out;
  }
  /**
   * Creates a new Seismogram composed of all seismogram segments that overlap the
   * given time window. If none do, this returns null. This is a faster but coarser
   * version of cut as it only removes whole segments that do not overlap the
   * time window. For most seismograms that consist of a single contiguous
   * data segment, this will do nothing.
   *
   * @param timeRange time range to trim to
   * @returns new seismogram if data in the window, null otherwise
   * @see cut
   */
  trim(timeRange) {
    let out = null;
    checkLuxonValid(timeRange);
    const timeRange_start = validStartTime(timeRange);
    const timeRange_end = validEndTime(timeRange);
    if (this._segmentArray) {
      const trimSeisArray = this._segmentArray.filter(function(d) {
        return d.endTime >= timeRange_start;
      }).filter(function(d) {
        return d.startTime <= timeRange_end;
      });
      if (trimSeisArray.length > 0) {
        out = new _Seismogram(trimSeisArray);
      }
    }
    return out;
  }
  break(duration3) {
    if (duration3.valueOf() < 0) {
      throw new Error(`Negative duration not allowed: ${duration3.toString()}`);
    }
    if (this._segmentArray) {
      let breakStart = this.startTime;
      let out = [];
      while (breakStart < this.endTime) {
        const breakWindow = Interval.after(breakStart, duration3);
        const cutSeisArray = this._segmentArray.map((seg) => seg.cut(breakWindow)).filter(isDef);
        out = out.concat(cutSeisArray);
        breakStart = breakStart.plus(duration3);
      }
      out = out.filter(isDef);
      this._segmentArray = out;
    }
  }
  isContiguous() {
    if (this._segmentArray.length === 1) {
      return true;
    }
    let prev = null;
    for (const s2 of this._segmentArray) {
      if (prev && !(prev.endTime < s2.startTime && prev.endTime.plus(
        Duration.fromMillis(1e3 * 1.5 / prev.sampleRate)
      ) > s2.startTime)) {
        return false;
      }
      prev = s2;
    }
    return true;
  }
  /**
   * Merges all segments into a single array of the same type as the first
   * segment. No checking is done for gaps or overlaps, this is a simple
   * concatination. Be careful!
   *
   * @returns contatenated data
   */
  merge() {
    let outArray;
    let idx = 0;
    if (this._segmentArray.every((seg) => seg.y instanceof Int32Array)) {
      outArray = new Int32Array(this.numPoints);
      this._segmentArray.forEach((seg) => {
        outArray.set(seg.y, idx);
        idx += seg.y.length;
      });
    } else if (this._segmentArray.every((seg) => seg.y instanceof Float32Array)) {
      outArray = new Float32Array(this.numPoints);
      this._segmentArray.forEach((seg) => {
        outArray.set(seg.y, idx);
        idx += seg.y.length;
      });
    } else if (this._segmentArray.every((seg) => seg.y instanceof Float64Array)) {
      outArray = new Float64Array(this.numPoints);
      this._segmentArray.forEach((seg) => {
        outArray.set(seg.y, idx);
        idx += seg.y.length;
      });
    } else {
      throw new Error(
        `data not all same one of Int32Array, Float32Array or Float64Array`
      );
    }
    return outArray;
  }
  /**
   * Gets the timeseries as an typed array if it is contiguous.
   *
   * @throws {NonContiguousData} if data is not contiguous.
   * @returns  timeseries as array of number
   */
  get y() {
    if (!this._y) {
      if (this.isContiguous()) {
        this._y = this.merge();
      }
    }
    if (this._y) {
      return this._y;
    } else {
      throw new Error(
        "Seismogram is not contiguous, access each SeismogramSegment idividually."
      );
    }
  }
  set y(val) {
    throw new Error("seismogram y setter not impl, see cloneWithNewData()");
  }
  clone() {
    const cloned = this._segmentArray.map((s2) => s2.clone());
    return new _Seismogram(cloned);
  }
  cloneWithNewData(newY) {
    if (newY && newY.length > 0) {
      const seg = this._segmentArray[0].cloneWithNewData(newY);
      return new _Seismogram([seg]);
    } else {
      throw new Error("Y value is empty");
    }
  }
  /**
   * factory method to create a single segment Seismogram from either encoded data
   *  or a TypedArray, along with sample rate and start time.
   *
   * @param yArray array of encoded data or typed array
   * @param sampleRate sample rate, samples per second of the data
   * @param startTime time of first sample
   * @param sourceId optional source id
   * @returns seismogram initialized with the data
   */
  static fromContiguousData(yArray, sampleRate, startTime, sourceId) {
    const seg = new SeismogramSegment(yArray, sampleRate, startTime, sourceId);
    return new _Seismogram([seg]);
  }
};
var NonContiguousData = class extends Error {
  constructor(message) {
    super(message);
    this.name = this.constructor.name;
  }
};
function ensureIsSeismogram(seisSeismogram) {
  if (typeof seisSeismogram === "object") {
    if (seisSeismogram instanceof Seismogram) {
      return seisSeismogram;
    } else if (seisSeismogram instanceof SeismogramSegment) {
      return new Seismogram([seisSeismogram]);
    } else {
      throw new Error(
        "must be Seismogram or SeismogramSegment but " + stringify(seisSeismogram)
      );
    }
  } else {
    throw new Error(
      "must be Seismogram or SeismogramSegment but not an object: " + stringify(seisSeismogram)
    );
  }
}
var SeismogramDisplayData = class _SeismogramDisplayData {
  constructor(timeRange) {
    this.quakeReferenceList = [];
    if (!timeRange) {
      throw new Error("timeRange must not be missing.");
    }
    checkLuxonValid(timeRange);
    this._id = null;
    this._sourceId = null;
    this._seismogram = null;
    this.label = null;
    this.markerList = [];
    this.traveltimeList = [];
    this.channel = null;
    this._instrumentSensitivity = null;
    this.quakeList = [];
    this.timeRange = timeRange;
    this.alignmentTime = validStartTime(timeRange);
    this.doShow = true;
    this._statsCache = null;
  }
  static fromSeismogram(seismogram) {
    const out = new _SeismogramDisplayData(
      Interval.fromDateTimes(seismogram.startTime, seismogram.endTime)
    );
    out.seismogram = seismogram;
    return out;
  }
  /**
   * Create a Seismogram from the segment, then call fromSeismogram to create
   * the SeismogramDisplayData;
   * @param  seisSegment segment of contiguous data
   * @returns             new SeismogramDisplayData
   */
  static fromSeismogramSegment(seisSegment) {
    return _SeismogramDisplayData.fromSeismogram(new Seismogram([seisSegment]));
  }
  /**
   * Useful for creating fake data from an array, sample rate and start time
   *
   * @param yArray fake data
   * @param sampleRate samples per second
   * @param startTime  start of data, time of first point
   * @param sourceId  optional source id
   * @returns seismogramdisplaydata
   */
  static fromContiguousData(yArray, sampleRate, startTime, sourceId) {
    return _SeismogramDisplayData.fromSeismogram(
      Seismogram.fromContiguousData(yArray, sampleRate, startTime, sourceId)
    );
  }
  static fromChannelAndTimeWindow(channel, timeRange) {
    if (!channel) {
      throw new Error("fromChannelAndTimeWindow, channel is undef");
    }
    const out = new _SeismogramDisplayData(timeRange);
    out.channel = channel;
    return out;
  }
  static fromChannelAndTimes(channel, startTime, endTime) {
    const out = new _SeismogramDisplayData(
      Interval.fromDateTimes(startTime, endTime)
    );
    out.channel = channel;
    return out;
  }
  static fromSourceIdAndTimes(sourceId, startTime, endTime) {
    const out = new _SeismogramDisplayData(
      Interval.fromDateTimes(startTime, endTime)
    );
    out._sourceId = sourceId;
    return out;
  }
  static fromCodesAndTimes(networkCode, stationCode, locationCode, channelCode, startTime, endTime) {
    const out = new _SeismogramDisplayData(
      Interval.fromDateTimes(startTime, endTime)
    );
    out._sourceId = FDSNSourceId.fromNslc(
      networkCode,
      stationCode,
      locationCode,
      channelCode
    );
    return out;
  }
  addQuake(quake) {
    if (Array.isArray(quake)) {
      quake.forEach((q) => this.quakeList.push(q));
    } else {
      this.quakeList.push(quake);
    }
  }
  /**
   * Adds a public id for a Quake to the seismogram. For use in case where
   * the quake is not yet available, but wish to retain the connection.
   * @param  publicId  id of the earthquake assocated with this seismogram
   */
  addQuakeId(publicId) {
    this.quakeReferenceList.push(publicId);
  }
  addMarker(marker2) {
    let mlist = [marker2];
    if (Array.isArray(marker2)) {
      mlist = marker2;
    }
    this.addMarkers(mlist);
  }
  addMarkers(markers) {
    if (Array.isArray(markers)) {
      markers.forEach((m) => this.markerList.push(m));
    } else {
      this.markerList.push(markers);
    }
  }
  getMarkers() {
    return this.markerList;
  }
  clearMarkers() {
    this.markerList = [];
  }
  addTravelTimes(ttimes) {
    if (Array.isArray(ttimes)) {
      ttimes.forEach((m) => this.traveltimeList.push(m));
    } else if ("arrivals" in ttimes) {
      ttimes.arrivals.forEach((m) => this.traveltimeList.push(m));
    } else {
      this.traveltimeList.push(ttimes);
    }
  }
  hasQuake() {
    return this.quakeList.length > 0;
  }
  get quake() {
    if (this.hasQuake()) {
      return this.quakeList[0];
    }
    return null;
  }
  hasSeismogram() {
    return isDef(this._seismogram);
  }
  append(seismogram) {
    if (isDef(this._seismogram)) {
      this._seismogram.append(seismogram);
      if (this.startTime > seismogram.startTime || this.endTime < seismogram.endTime) {
        const startTime = this.startTime < seismogram.startTime ? this.startTime : seismogram.startTime;
        const endTime = this.endTime > seismogram.endTime ? this.endTime : seismogram.endTime;
        this.timeRange = Interval.fromDateTimes(startTime, endTime);
      }
    } else {
      if (seismogram instanceof SeismogramSegment) {
        this.seismogram = new Seismogram(seismogram);
      } else {
        this.seismogram = seismogram;
      }
    }
    this._statsCache = null;
  }
  hasChannel() {
    return isDef(this.channel);
  }
  hasSensitivity() {
    return this._instrumentSensitivity !== null || isDef(this.channel) && this.channel.hasInstrumentSensitivity();
  }
  /**
   * Allows id-ing a seismogram. Optional.
   *
   * @returns         string id
   */
  get id() {
    return this._id;
  }
  /**
   * Allows iding a seismogram. Optional.
   *
   * @param   value string id
   */
  set id(value) {
    this._id = value;
  }
  /**
   * return network code as a string.
   * Uses this.channel if it exists, this.seismogram if not.
   *
   * @returns network code
   */
  get networkCode() {
    let out = this.sourceId.networkCode;
    if (!isDef(out)) {
      out = "unknown";
    }
    return out;
  }
  /**
   * return station code as a string.
   * Uses this.channel if it exists, this.seismogram if not.
   *
   * @returns station code
   */
  get stationCode() {
    let out = this.sourceId.stationCode;
    if (!isDef(out)) {
      out = "unknown";
    }
    return out;
  }
  /**
   * return location code a a string.
   * Uses this.sourceId if it exists, this.seismogram if not.
   *
   * @returns location code
   */
  get locationCode() {
    let out = this?.sourceId.locationCode;
    if (!isDef(out)) {
      out = "unknown";
    }
    return out;
  }
  /**
   * return channels code as a string.
   * Uses this.sourceId if it exists, this.seismogram if not.
   *
   * @returns channel code
   */
  get channelCode() {
    let out = this?.sourceId.formChannelCode();
    if (!isDef(out)) {
      out = "unknown";
    }
    return out;
  }
  /**
   * return FDSN source id as a string.
   * Uses this.channel if it exists, this.seismogram if not.
   *
   * @returns FDSN source id
   */
  get sourceId() {
    if (isDef(this.channel)) {
      return this.channel.sourceId;
    } else if (isDef(this._seismogram)) {
      return this._seismogram.sourceId;
    } else if (isDef(this._sourceId)) {
      return this._sourceId;
    } else {
      return FDSNSourceId.createUnknown();
    }
  }
  /**
   * return network, station, location and channels codes as one string.
   * Uses this.channel if it exists, this.seismogram if not
   *
   * @returns net.sta.loc.chan
   */
  get nslc() {
    return this.codes();
  }
  get nslcId() {
    if (this.channel !== null) {
      return this.channel.nslcId;
    } else {
      return new NslcId(
        this.networkCode ? this.networkCode : "",
        this.stationCode ? this.stationCode : "",
        this.locationCode && this.locationCode !== "--" ? this.locationCode : "",
        this.channelCode ? this.channelCode : ""
      );
    }
  }
  /**
   * return network, station, location and channels codes as one string.
   * Uses this.channel if it exists, this.seismogram if not.
   *
   * @param sep separator, defaults to '.'
   * @returns nslc codes separated by sep
   */
  codes(sep = ".") {
    if (this.channel !== null) {
      return this.channel.codes();
    } else {
      return (this.networkCode ? this.networkCode : "") + sep + (this.stationCode ? this.stationCode : "") + sep + (this.locationCode ? this.locationCode : "") + sep + (this.channelCode ? this.channelCode : "");
    }
  }
  get startTime() {
    return validStartTime(this.timeRange);
  }
  get start() {
    return this.startTime;
  }
  get endTime() {
    return validEndTime(this.timeRange);
  }
  get end() {
    return this.endTime;
  }
  get numPoints() {
    if (this._seismogram) {
      return this._seismogram.numPoints;
    }
    return 0;
  }
  associateChannel(nets) {
    const matchChans = findChannels(
      nets,
      this.networkCode,
      this.stationCode,
      this.locationCode,
      this.channelCode
    );
    for (const c of matchChans) {
      if (c.timeRange.overlaps(this.timeRange)) {
        this.channel = c;
        return;
      }
    }
  }
  alignStartTime() {
    this.alignmentTime = this.start;
  }
  alignOriginTime() {
    if (this.quake) {
      this.alignmentTime = this.quake.time;
    } else {
      this.alignmentTime = this.start;
    }
  }
  alignPhaseTime(phaseRegExp) {
    let intPhaseRegExp;
    if (typeof phaseRegExp === "string") {
      intPhaseRegExp = new RegExp(phaseRegExp);
    } else {
      intPhaseRegExp = phaseRegExp;
    }
    if (this.quake && this.traveltimeList) {
      const q = this.quake;
      const matchArrival = this.traveltimeList.find((ttArrival) => {
        const match2 = intPhaseRegExp.exec(ttArrival.phase);
        return match2 !== null && match2[0] === ttArrival.phase;
      });
      if (matchArrival) {
        this.alignmentTime = q.time.plus(
          Duration.fromMillis(matchArrival.time * 1e3)
        );
      } else {
        this.alignmentTime = this.start;
      }
    }
  }
  /**
   * Create a time window relative to the alignmentTime if set, or the start time if not.
   * Negative durations are allowed.
   * @param alignmentOffset offset duration from the alignment time
   * @param duration duration from the offset for the window
   * @returns time window as an Interval
   */
  relativeTimeWindow(alignmentOffset, duration3) {
    const atime = this.alignmentTime ? this.alignmentTime.plus(alignmentOffset) : this.startTime.plus(alignmentOffset);
    return startDuration(atime, duration3);
  }
  get sensitivity() {
    const channel = this.channel;
    if (this._instrumentSensitivity) {
      return this._instrumentSensitivity;
    } else if (isDef(channel) && channel.hasInstrumentSensitivity()) {
      return channel.instrumentSensitivity;
    } else {
      return null;
    }
  }
  set sensitivity(value) {
    this._instrumentSensitivity = value;
  }
  get min() {
    if (!this._statsCache) {
      this._statsCache = this.calcStats();
    }
    return this._statsCache.min;
  }
  get max() {
    if (!this._statsCache) {
      this._statsCache = this.calcStats();
    }
    return this._statsCache.max;
  }
  get mean() {
    if (!this._statsCache) {
      this._statsCache = this.calcStats();
    }
    return this._statsCache.mean;
  }
  get middle() {
    if (!this._statsCache) {
      this._statsCache = this.calcStats();
    }
    return this._statsCache.middle;
  }
  get seismogram() {
    return this._seismogram;
  }
  set seismogram(value) {
    this._seismogram = value;
    this._statsCache = null;
  }
  get segments() {
    if (this._seismogram) {
      return this._seismogram.segments;
    } else {
      return [];
    }
  }
  calcStats() {
    const stats = new SeismogramDisplayStats();
    if (this.seismogram) {
      const minMax = this.seismogram.findMinMax();
      stats.min = minMax.min;
      stats.max = minMax.max;
      stats.mean = this.seismogram.mean();
    }
    this._statsCache = stats;
    return stats;
  }
  /**
   * Calculates distance and azimuth for each event in quakeList.
   *
   * @returns Array of DistAzOutput, empty array if no quakes.
   */
  get distazList() {
    if (this.quakeList.length > 0 && isDef(this.channel)) {
      const c = this.channel;
      return this.quakeList.map(
        (q) => distaz(c.latitude, c.longitude, q.latitude, q.longitude)
      );
    }
    return [];
  }
  /**
   * Calculates distance and azimuth for the first event in quakeList. This is
   * a convienence method as usually there will only be one quake.
   *
   * @returns DistAzOutput, null if no quakes.
   */
  get distaz() {
    let out = null;
    if (this.quakeList.length > 0 && this.channel !== null) {
      out = distaz(
        this.channel.latitude,
        this.channel.longitude,
        this.quakeList[0].latitude,
        this.quakeList[0].longitude
      );
    }
    return out;
  }
  clone() {
    return this.cloneWithNewSeismogram(
      this.seismogram ? this.seismogram.clone() : null
    );
  }
  cloneWithNewSeismogram(seis) {
    const out = new _SeismogramDisplayData(this.timeRange);
    const handled = ["_seismogram", "_statsCache", "_sourceId"];
    Object.assign(out, this);
    Object.getOwnPropertyNames(this).forEach((name) => {
      const v = this[name];
      if (handled.find((n2) => name === n2)) {
      } else if (Array.isArray(v)) {
        out[name] = v.slice();
      }
    });
    out.seismogram = seis;
    out._statsCache = null;
    if (!isDef(out._seismogram) && !isDef(out.channel)) {
      if (this.sourceId) {
        out._sourceId = this.sourceId.clone();
      }
    }
    return out;
  }
  /**
   * Cut the seismogram. Creates a new seismogramDisplayData with the cut
   * seismogram and the timeRange set to the new time window.
   *
   * @param  timeRange start and end of cut
   * @returns           new seismogramDisplayData
   */
  cut(timeRange) {
    let cutSeis = this.seismogram;
    let out;
    if (cutSeis) {
      cutSeis = cutSeis.cut(timeRange);
      out = this.cloneWithNewSeismogram(cutSeis);
      if (!isDef(out._seismogram) && !isDef(out.channel)) {
        out._sourceId = this.sourceId;
      }
    } else {
      out = this.clone();
    }
    out.timeRange = timeRange;
    return out;
  }
  /**
   * Coarse trim the seismogram. Creates a new seismogramDisplayData with the
   * trimmed seismogram and the timeRange set to the new time window.
   * If timeRange is not given, the current time range of the
   * SeismogramDisplayData is used, effectively trimming data to the current
   * window.
   *
   * @param  timeRange start and end of cut
   * @returns           new seismogramDisplayData
   */
  trim(timeRange) {
    if (!timeRange) {
      timeRange = this.timeRange;
    }
    let cutSeis = this.seismogram;
    let out;
    if (cutSeis) {
      cutSeis = cutSeis.trim(timeRange);
      out = this.cloneWithNewSeismogram(cutSeis);
      if (!isDef(out._seismogram) && !isDef(out.channel)) {
        out._sourceId = this.sourceId;
      }
    } else {
      out = this.clone();
    }
    out.timeRange = timeRange;
    return out;
  }
  /**
   * Coarse trim the seismogram in place. The seismogram is
   * trimmed to the given time window.
   * If timeRange is not given, the current time range of the
   * SeismogramDisplayData is used, effectively trimming data to the current
   * window.
   *
   * @param  timeRange start and end of cut
   */
  trimInPlace(timeRange) {
    if (!timeRange) {
      timeRange = this.timeRange;
    }
    const cutSeis = this.seismogram;
    if (cutSeis) {
      this.seismogram = cutSeis.trim(timeRange);
    }
  }
  toString() {
    return `${this.sourceId.toString()} ${this.timeRange.toString()}`;
  }
};
var SeismogramDisplayStats = class {
  constructor() {
    this.min = 0;
    this.max = 0;
    this.mean = 0;
    this.trendSlope = 0;
  }
  get middle() {
    return (this.min + this.max) / 2;
  }
};
function findStartEnd(sddList) {
  if (sddList.length === 0) {
    return Interval.before(DateTime.utc(), 0);
  }
  return sddList.reduce(
    (acc, sdd) => acc.union(sdd.timeRange),
    sddList[0].timeRange
  );
}
function findMaxDuration(sddList) {
  return findMaxDurationOfType("start", sddList);
}
function findMaxDurationOfType(type, sddList) {
  return sddList.reduce((acc, sdd) => {
    let timeRange;
    if (type === "start") {
      timeRange = sdd.timeRange;
    } else if (type === "origin" && sdd.hasQuake()) {
      timeRange = Interval.fromDateTimes(
        sdd.quakeList[0].time,
        validEndTime(sdd.timeRange)
      );
    } else if (type === "align" && sdd.alignmentTime) {
      timeRange = Interval.fromDateTimes(
        sdd.alignmentTime,
        validEndTime(sdd.timeRange)
      );
    } else {
      timeRange = sdd.timeRange;
    }
    if (timeRange.toDuration().toMillis() > acc.toMillis()) {
      return timeRange.toDuration();
    } else {
      return acc;
    }
  }, Duration.fromMillis(0));
}
function findMinMax(sddList, doGain = false, amplitudeMode = "minmax" /* MinMax */) {
  return findMinMaxOverTimeRange(sddList, null, doGain, amplitudeMode);
}
function findMinMaxOverTimeRange(sddList, timeRange = null, doGain = false, amplitudeMode = "minmax" /* MinMax */) {
  if (sddList.length === 0) {
    return new MinMaxable(-1, 1);
  }
  const minMaxArr = sddList.map((sdd) => {
    return calcMinMax(sdd, timeRange, doGain, amplitudeMode);
  }).filter((x2) => x2).reduce(function(p, v) {
    if (amplitudeMode === "raw" /* Raw */ || amplitudeMode === "zero" /* Zero */) {
      return p ? v ? p.union(v) : p : v;
    } else {
      let hw;
      if (p && v) {
        hw = Math.max(p.halfWidth, v.halfWidth);
      } else if (p) {
        hw = p.halfWidth;
      } else if (v) {
        hw = v.halfWidth;
      } else {
        hw = 0;
      }
      return MinMaxable.fromMiddleHalfWidth(0, hw);
    }
  }, null);
  if (minMaxArr) {
    return minMaxArr;
  }
  return new MinMaxable(-1, 1);
}
function findMinMaxOverRelativeTimeRange(sddList, alignmentOffset, duration3, doGain = false, amplitudeMode = "minmax" /* MinMax */) {
  if (sddList.length === 0) {
    return new MinMaxable(0, 0);
  }
  const minMaxArr = sddList.map((sdd) => {
    const timeRange = sdd.relativeTimeWindow(alignmentOffset, duration3);
    return calcMinMax(sdd, timeRange, doGain, amplitudeMode);
  }).filter((x2) => x2).reduce(function(p, v) {
    if (amplitudeMode === "raw" /* Raw */ || amplitudeMode === "zero" /* Zero */) {
      return p ? v ? p.union(v) : p : v;
    } else {
      let hw;
      if (p && v) {
        hw = Math.max(p.halfWidth, v.halfWidth);
      } else if (p) {
        hw = p.halfWidth;
      } else if (v) {
        hw = v.halfWidth;
      } else {
        hw = 0;
      }
      return MinMaxable.fromMiddleHalfWidth(0, hw);
    }
  }, null);
  if (minMaxArr) {
    return minMaxArr;
  }
  return new MinMaxable(-1, 1);
}
function calcMinMax(sdd, timeRange = null, doGain = false, amplitudeMode = "minmax" /* MinMax */) {
  if (sdd.seismogram) {
    let cutSDD;
    if (timeRange) {
      cutSDD = sdd.cut(timeRange);
    } else {
      cutSDD = sdd;
    }
    if (cutSDD) {
      let sens = 1;
      if (doGain && sdd.sensitivity) {
        sens = sdd.sensitivity.sensitivity;
      }
      let middle;
      let halfWidth;
      if (amplitudeMode === "minmax" /* MinMax */ || amplitudeMode === "raw" /* Raw */) {
        middle = cutSDD.middle;
        halfWidth = Math.max(
          (middle - cutSDD.min) / sens,
          (cutSDD.max - middle) / sens
        );
      } else if (amplitudeMode === "mean" /* Mean */) {
        middle = sdd.mean;
        halfWidth = Math.max(
          (middle - cutSDD.min) / sens,
          (cutSDD.max - middle) / sens
        );
      } else if (amplitudeMode === "zero" /* Zero */) {
        const minwz = Math.min(0, cutSDD.min);
        const maxwz = Math.max(0, cutSDD.max);
        middle = (minwz + maxwz) / 2;
        halfWidth = (maxwz - minwz) / 2 / sens;
      } else {
        throw new Error(
          `Unknown amplitudeMode: ${stringify(amplitudeMode)}. Must be one of raw, zero, minmax, mean`
        );
      }
      return MinMaxable.fromMiddleHalfWidth(middle, halfWidth);
    }
  }
  return null;
}
function findStartEndOfSeismograms(data, accumulator) {
  let out;
  if (accumulator == null && data == null) {
    throw new Error("data and accumulator are not defined");
  } else if (accumulator == null) {
    if (data.length !== 0) {
      out = data[0].timeRange;
    } else {
      throw new Error("data.length == 0 and accumulator is not defined");
    }
  } else {
    out = accumulator;
  }
  if (Array.isArray(data)) {
    out = data.reduce(
      (acc, cur) => acc.union(cur.timeRange),
      out
    );
  } else {
    throw new Error(`Expected Array as first arg but was: ${typeof data}`);
  }
  return out;
}
function findMinMaxOfSeismograms(data, minMaxAccumulator) {
  for (const s2 of data) {
    minMaxAccumulator = s2.findMinMax(minMaxAccumulator);
  }
  if (minMaxAccumulator) {
    return minMaxAccumulator;
  } else {
    return new MinMaxable(-1, 1);
  }
}
function findMinMaxOfSDD(data, minMaxAccumulator) {
  const seisData = [];
  data.forEach((sdd) => {
    if (!!sdd && !!sdd.seismogram) {
      seisData.push(sdd.seismogram);
    }
  });
  return findMinMaxOfSeismograms(seisData, minMaxAccumulator);
}
function uniqueStations2(seisData) {
  const out = /* @__PURE__ */ new Set();
  seisData.forEach((sdd) => {
    if (sdd.channel) {
      out.add(sdd.channel.station);
    }
  });
  return Array.from(out.values());
}
function uniqueChannels(seisData) {
  const out = /* @__PURE__ */ new Set();
  seisData.forEach((sdd) => {
    if (sdd.channel) {
      out.add(sdd.channel);
    }
  });
  return Array.from(out.values());
}
function uniqueLocationCodes(seisData) {
  const out = /* @__PURE__ */ new Set();
  seisData.forEach((sdd) => {
    out.add(sdd.sourceId.locationCode);
  });
  return Array.from(out.values());
}
function uniqueBandCodes(seisData) {
  const out = /* @__PURE__ */ new Set();
  seisData.forEach((sdd) => {
    out.add(sdd.sourceId.bandCode);
  });
  return Array.from(out.values());
}
function uniqueSourceCodes(seisData) {
  const out = /* @__PURE__ */ new Set();
  seisData.forEach((sdd) => {
    out.add(sdd.sourceId.sourceCode);
  });
  return Array.from(out.values());
}
function uniqueSubsourceCodes(seisData) {
  const out = /* @__PURE__ */ new Set();
  seisData.forEach((sdd) => {
    out.add(sdd.sourceId.subsourceCode);
  });
  return Array.from(out.values());
}
function uniqueSourceIds2(seisData) {
  const out = /* @__PURE__ */ new Map();
  seisData.forEach((sdd) => {
    out.set(sdd.sourceId.toString(), sdd.sourceId);
  });
  return Array.from(out.values());
}
function uniqueQuakes(seisData) {
  const out = /* @__PURE__ */ new Set();
  seisData.forEach((sdd) => {
    sdd.quakeList.forEach((q) => out.add(q));
  });
  return Array.from(out.values());
}

// src/miniseed.mts
var MINISEED_MIME = "application/vnd.fdsn.mseed";
var R_TYPECODE = "R".charCodeAt(0);
var D_TYPECODE = "D".charCodeAt(0);
var Q_TYPECODE = "Q".charCodeAt(0);
var M_TYPECODE = "M".charCodeAt(0);
function parseDataRecords(arrayBuffer) {
  const dataRecords = [];
  let offset2 = 0;
  while (offset2 < arrayBuffer.byteLength) {
    const dataView = new DataView(arrayBuffer, offset2);
    const dr = parseSingleDataRecord(dataView);
    dataRecords.push(dr);
    offset2 += dr.header.recordSize;
  }
  return dataRecords;
}
function parseSingleDataRecord(dataView) {
  const header = parseSingleDataRecordHeader(dataView);
  const data = new DataView(
    dataView.buffer,
    dataView.byteOffset + header.dataOffset,
    header.recordSize - header.dataOffset
  );
  return new DataRecord(header, data);
}
function parseSingleDataRecordHeader(dataView) {
  if (dataView.byteLength < 47) {
    throw new Error(
      `Not enought bytes for header, need 47, found ${dataView.byteLength}`
    );
  }
  const out = new DataHeader();
  out.seq = makeString(dataView, 0, 6);
  out.typeCode = dataView.getUint8(6);
  out.continuationCode = dataView.getUint8(7);
  out.staCode = makeString(dataView, 8, 5);
  out.locCode = makeString(dataView, 13, 2);
  out.chanCode = makeString(dataView, 15, 3);
  out.netCode = makeString(dataView, 18, 2);
  out.startBTime = parseBTime(dataView, 20);
  const headerByteSwap = checkByteSwap(out.startBTime);
  if (headerByteSwap) {
    out.startBTime = parseBTime(dataView, 20, headerByteSwap);
  }
  out.numSamples = dataView.getInt16(30, headerByteSwap);
  out.sampRateFac = dataView.getInt16(32, headerByteSwap);
  out.sampRateMul = dataView.getInt16(34, headerByteSwap);
  out.activityFlags = dataView.getUint8(36);
  out.ioClockFlags = dataView.getUint8(37);
  out.dataQualityFlags = dataView.getUint8(38);
  out.numBlockettes = dataView.getUint8(39);
  out.timeCorrection = dataView.getInt32(40, headerByteSwap);
  out.dataOffset = dataView.getUint16(44, headerByteSwap);
  out.blocketteOffset = dataView.getUint16(46, headerByteSwap);
  let offset2 = out.blocketteOffset;
  out.blocketteList = [];
  out.recordSize = 4096;
  out.sampleRate = out.calcSampleRate();
  out.startTime = out.startBTime.toDateTime();
  for (let i = 0; i < out.numBlockettes; i++) {
    let nextOffset = dataView.getUint16(offset2 + 2, headerByteSwap);
    if (nextOffset === 0) {
      nextOffset = out.dataOffset;
    }
    if (nextOffset === 0) {
      nextOffset = offset2;
    }
    const blockette = parseBlockette(
      dataView,
      offset2,
      nextOffset - offset2,
      headerByteSwap
    );
    out.blocketteList.push(blockette);
    offset2 = nextOffset;
    if (blockette instanceof Blockette1000) {
      out.recordSize = 1 << blockette.dataRecordLengthByte;
      out.encoding = blockette.encoding;
      out.littleEndian = blockette.wordOrder === 0;
    } else if (blockette instanceof Blockette1001) {
      out.startBTime.microsecond = blockette.microsecond;
    } else if (blockette instanceof Blockette100) {
      out.sampleRate = blockette.sampleRate;
    }
  }
  out.endTime = out.timeOfSample(out.numSamples - 1);
  return out;
}
function parseBlockette(dataView, offset2, length, headerByteSwap) {
  const type = dataView.getUint16(offset2, headerByteSwap);
  const body = new DataView(
    dataView.buffer,
    dataView.byteOffset + offset2,
    length
  );
  if (type === 1e3) {
    const encoding = body.getUint8(4);
    const wordOrder = body.getUint8(5);
    const dataRecordLengthByte = body.getUint8(6);
    return new Blockette1000(
      type,
      body,
      encoding,
      dataRecordLengthByte,
      wordOrder
    );
  } else if (type === 1001) {
    const timeQual = body.getUint8(4);
    const microsecond = body.getUint8(5);
    const frameCount = body.getUint8(7);
    return new Blockette1001(type, body, timeQual, microsecond, frameCount);
  } else if (type === 100) {
    const sampleRate = body.getFloat32(4);
    const flags = body.getUint8(8);
    return new Blockette100(type, body, sampleRate, flags);
  } else {
    return new Blockette(type, body);
  }
}
var DataRecord = class {
  constructor(header, data) {
    this.header = header;
    this.data = data;
  }
  /**
   * Decompresses the data , if the compression type is known.
   *
   * @returns decompressed data
   */
  decompress() {
    return this.asEncodedDataSegment().decode();
  }
  asEncodedDataSegment() {
    return new EncodedDataSegment(
      this.header.encoding,
      this.data,
      this.header.numSamples,
      this.header.littleEndian
    );
  }
  /**
   * Concatenates the net, station, loc and channel codes,
   * separated by the given seperator, or periods if not given.
   *
   * @param sep optional separater, defaults to .
   * @returns string of codes
   */
  codes(sep) {
    if (!isNonEmptyStringArg(sep)) {
      sep = ".";
    }
    return this.header.netCode + sep + this.header.staCode + sep + this.header.locCode + sep + this.header.chanCode;
  }
};
var DataHeader = class {
  constructor() {
    this.seq = "      ";
    this.typeCode = 68;
    this.continuationCode = 32;
    this.staCode = "";
    this.locCode = "";
    this.chanCode = "";
    this.netCode = "";
    this.startBTime = new BTime(1900, 1, 0, 0, 0, 0);
    this.numSamples = 0;
    this.sampRateFac = 0;
    this.sampRateMul = 0;
    this.activityFlags = 0;
    this.ioClockFlags = 0;
    this.dataQualityFlags = 0;
    this.numBlockettes = 0;
    this.timeCorrection = 0;
    this.dataOffset = 0;
    this.blocketteOffset = 0;
    this.blocketteList = [];
    this.recordSize = 4096;
    this.encoding = 0;
    this.littleEndian = false;
    this.sampleRate = 0;
    this.startTime = this.startBTime.toDateTime();
    this.endTime = this.startTime;
  }
  toString() {
    return `${this.netCode}.${this.staCode}.${this.locCode}.${this.chanCode} ${this.startTime.toISO()} ${String(this.encoding)}`;
  }
  /**
   * Calculates the sample rate in hertz from the sampRateFac and sampRateMul
   * parameters. This.sampleRate value is set to this value at construction.
   *
   * @returns sample rate
   */
  calcSampleRate() {
    const factor = this.sampRateFac;
    const multiplier = this.sampRateMul;
    let sampleRate = 1e4;
    if (factor * multiplier !== 0) {
      sampleRate = Math.pow(Math.abs(factor), factor / Math.abs(factor)) * Math.pow(Math.abs(multiplier), multiplier / Math.abs(multiplier));
    }
    return sampleRate;
  }
  /**
   * Calculates the time of the i-th sample in the record, zero based,
   *  so timeOfSample(0) is the start and timeOfSample(this.numSamples-1) is end.
   *
   * @param i sample index
   * @returns time at i-th sample as DateTime
   */
  timeOfSample(i) {
    return this.startTime.plus(
      Duration.fromMillis(1e3 * i / this.sampleRate)
    );
  }
};
var Blockette = class {
  constructor(type, body) {
    this.type = type;
    this.body = body;
  }
};
var Blockette1000 = class extends Blockette {
  constructor(type, body, encoding, dataRecordLengthByte, wordOrder) {
    super(type, body);
    if (type !== 1e3) {
      throw new Error("Not a blockette1000: " + this.type);
    }
    this.encoding = encoding;
    this.dataRecordLengthByte = dataRecordLengthByte;
    this.wordOrder = wordOrder;
  }
};
var Blockette1001 = class extends Blockette {
  constructor(type, body, timeQual, microsecond, frameCount) {
    super(type, body);
    if (type !== 1001) {
      throw new Error("Not a blockette1001: " + this.type);
    }
    this.timeQual = timeQual;
    this.microsecond = microsecond;
    this.frameCount = frameCount;
  }
};
var Blockette100 = class extends Blockette {
  constructor(type, body, sampleRate, flags) {
    super(type, body);
    if (type !== 100) {
      throw new Error("Not a blockette100: " + this.type);
    }
    this.sampleRate = sampleRate;
    this.flags = flags;
  }
};
function makeString(dataView, offset2, length) {
  let out = "";
  for (let i = offset2; i < offset2 + length; i++) {
    const charCode = dataView.getUint8(i);
    if (charCode > 31) {
      out += String.fromCharCode(charCode);
    }
  }
  return out.trim();
}
function parseBTime(dataView, offset2, byteSwap) {
  if (!isDef(byteSwap)) {
    byteSwap = false;
  }
  const year = dataView.getInt16(offset2, byteSwap);
  const jday = dataView.getInt16(offset2 + 2, byteSwap);
  const hour = dataView.getInt8(offset2 + 4);
  const min = dataView.getInt8(offset2 + 5);
  const sec = dataView.getInt8(offset2 + 6);
  const tenthMilli = dataView.getInt16(offset2 + 8, byteSwap);
  return new BTime(year, jday, hour, min, sec, tenthMilli);
}
var BTime = class {
  constructor(year, jday, hour, min, sec, tenthMilli) {
    this.length = 10;
    this.year = year;
    this.jday = jday;
    this.hour = hour;
    this.min = min;
    this.sec = sec;
    this.tenthMilli = tenthMilli;
    this.microsecond = 0;
  }
  toString() {
    return this.year + "-" + this.jday + " " + this.hour + ":" + this.min + ":" + this.sec + "." + this.tenthMilli.toFixed().padStart(4, "0") + " " + (this.microsecond !== 0 ? `usec: ${this.microsecond} ` : "") + "iso: " + this.toDateTime().toISO();
  }
  /**
   * Converts this BTime to a luxon utc DateTime. Note DateTime's precision
   * is limited to milliseconds and leap seconds are not supported,
   * ie 60 seconds returns DateTime.invalid.
   *
   * @returns         BTime as a DateTime
   */
  toDateTime() {
    const millis = Math.round(this.tenthMilli / 10);
    if (this.sec === 60) {
      return DateTime.invalid(
        "Leap seconds not supported",
        `seconds value ${this.sec} is a leap second, but luxon does not support`
      );
    }
    const d = DateTime.fromObject(
      {
        year: this.year,
        ordinal: this.jday,
        hour: this.hour,
        minute: this.min,
        second: this.sec,
        millisecond: 0
      },
      UTC_OPTIONS
    );
    return d.plus(millis);
  }
};
function checkByteSwap(bTime) {
  if (bTime.year === 1900 && bTime.jday === 1) {
    return false;
  }
  return bTime.year < 1960 || bTime.year > 2055;
}
function areContiguous(dr1, dr2) {
  const h1 = dr1.header;
  const h2 = dr2.header;
  return h1.endTime < h2.startTime && h1.endTime.valueOf() + 1e3 * 1.5 / h1.sampleRate > h2.startTime.valueOf();
}
function createSeismogramSegment(contig) {
  if (!Array.isArray(contig)) {
    contig = [contig];
  }
  const contigData = contig.map((dr) => dr.asEncodedDataSegment());
  const out = new SeismogramSegment(
    contigData,
    contig[0].header.sampleRate,
    contig[0].header.startTime,
    FDSNSourceId.fromNslc(
      contig[0].header.netCode,
      contig[0].header.staCode,
      contig[0].header.locCode,
      contig[0].header.chanCode
    )
  );
  return out;
}
function merge(drList) {
  return new Seismogram(mergeSegments(drList));
}
function mergeSegments(drList) {
  const out = [];
  let currDR;
  drList.sort(function(a, b) {
    return a.header.startTime.toMillis() - b.header.startTime.toMillis();
  });
  let contig = [];
  for (let i = 0; i < drList.length; i++) {
    currDR = drList[i];
    if (contig.length === 0) {
      contig.push(currDR);
    } else if (areContiguous(contig[contig.length - 1], currDR)) {
      contig.push(currDR);
    } else {
      out.push(createSeismogramSegment(contig));
      contig = [currDR];
    }
  }
  if (contig.length > 0) {
    out.push(createSeismogramSegment(contig));
  }
  return out;
}
function byChannel(drList) {
  const out = /* @__PURE__ */ new Map();
  let key;
  for (let i = 0; i < drList.length; i++) {
    const currDR = drList[i];
    key = currDR.codes();
    let drArray = out.get(key);
    if (!drArray) {
      drArray = [currDR];
      out.set(key, drArray);
    } else {
      drArray.push(currDR);
    }
  }
  return out;
}
function seismogramSegmentPerChannel(drList) {
  let out = new Array(0);
  const byChannelMap = byChannel(drList);
  byChannelMap.forEach(
    (segments) => out = out.concat(mergeSegments(segments))
  );
  return out;
}
function seismogramPerChannel(drList) {
  const out = [];
  const byChannelMap = byChannel(drList);
  byChannelMap.forEach((segments) => out.push(merge(segments)));
  return out;
}

// src/mseed3.mts
var mseed3_exports = {};
__export(mseed3_exports, {
  BIG_ENDIAN: () => BIG_ENDIAN,
  CRC_OFFSET: () => CRC_OFFSET,
  FDSN_PREFIX: () => FDSN_PREFIX2,
  FIXED_HEADER_SIZE: () => FIXED_HEADER_SIZE,
  LITTLE_ENDIAN: () => LITTLE_ENDIAN,
  MINISEED_THREE_MIME: () => MINISEED_THREE_MIME,
  MSeed3Header: () => MSeed3Header,
  MSeed3Record: () => MSeed3Record,
  UNKNOWN_DATA_VERSION: () => UNKNOWN_DATA_VERSION,
  areContiguous: () => areContiguous2,
  byChannel: () => byChannel2,
  calculateCRC32C: () => calculateCRC32C,
  convertMS2Record: () => convertMS2Record,
  convertMS2toMSeed3: () => convertMS2toMSeed3,
  crcToHexString: () => crcToHexString,
  createSeismogramSegment: () => createSeismogramSegment2,
  makeString: () => makeString2,
  merge: () => merge2,
  mergeSegments: () => mergeSegments2,
  mightBeMSeed3Records: () => mightBeMSeed3Records,
  padZeros: () => padZeros,
  parseExtraHeaders: () => parseExtraHeaders,
  parseMSeed3Records: () => parseMSeed3Records,
  sddPerChannel: () => sddPerChannel,
  seismogramPerChannel: () => seismogramPerChannel2,
  seismogramSegmentPerChannel: () => seismogramSegmentPerChannel2,
  toMSeed3: () => toMSeed3
});

// src/mseed3eh.mts
var mseed3eh_exports = {};
__export(mseed3eh_exports, {
  STD_EH: () => STD_EH,
  channelToEH: () => channelToEH,
  createBagEH: () => createBagEH,
  ehToChannel: () => ehToChannel,
  ehToMarkers: () => ehToMarkers,
  ehToQuake: () => ehToQuake,
  extractBagEH: () => extractBagEH,
  isValidBagChannelJsonEHType: () => isValidBagChannelJsonEHType,
  isValidBagEventJsonEHType: () => isValidBagEventJsonEHType,
  isValidBagJsonEHType: () => isValidBagJsonEHType,
  isValidBagMagJsonEHType: () => isValidBagMagJsonEHType,
  isValidBagMarkJsonEHType: () => isValidBagMarkJsonEHType,
  isValidBagOriginJsonEHType: () => isValidBagOriginJsonEHType,
  isValidBagPathJsonEHType: () => isValidBagPathJsonEHType,
  isValidBagTimeseriesJsonEHType: () => isValidBagTimeseriesJsonEHType,
  markerToEH: () => markerToEH,
  markerTypeFromEH: () => markerTypeFromEH,
  quakeToEH: () => quakeToEH
});
var STD_EH = "bag";
function ehToQuake(exHead) {
  const bag = extractBagEH(exHead);
  const origin = bag?.ev?.or;
  let q = null;
  if (origin != null) {
    const time3 = isoToDateTime(origin.tm);
    q = createQuakeFromValues("extraheader", time3, origin.la, origin.lo, origin.dp * 1e3);
    if (bag?.ev?.mag?.v != null) {
      const magtype = bag.ev.mag.t == null ? "" : bag.ev.mag.t;
      const mag = new Magnitude(bag.ev.mag.v, magtype);
      q.preferredMagnitude = mag;
    }
  }
  return q;
}
function quakeToEH(quake) {
  const ehEvent = {};
  if (quake.publicId != null) {
    ehEvent.id = quake.publicId;
  }
  if (quake.preferredOrigin != null) {
    const or = quake.origin;
    const isoTime = or.time.toISO();
    if (isoTime == null) {
      throw new Error(`Bad origin time: ${stringify(or.time)}`);
    }
    ehEvent.or = {
      tm: isoTime,
      la: or.latitude,
      lo: or.longitude,
      dp: or.depthKm
    };
  }
  if (quake.preferredMagnitude != null) {
    ehEvent.mag = {
      v: quake.preferredMagnitude.mag,
      t: quake.preferredMagnitude.type
    };
  }
  return ehEvent;
}
function channelToEH(channel) {
  return {
    la: channel.latitude,
    lo: channel.longitude,
    el: channel.elevation,
    dp: channel.depth,
    az: channel.azimuth,
    dip: channel.dip
  };
}
function ehToChannel(exHead, sid) {
  const bag = extractBagEH(exHead);
  const ch = bag?.ch;
  let channel = null;
  if (ch != null) {
    const net = new Network(sid.networkCode);
    const sta = new Station(net, sid.stationCode);
    sta.latitude = ch.la;
    sta.longitude = ch.lo;
    if (ch.el != null) {
      sta.elevation = ch.el;
    }
    channel = new Channel(sta, sid.formChannelCode(), sid.locationCode);
    channel.latitude = ch.la;
    channel.longitude = ch.lo;
    if (ch.dp != null) {
      channel.depth = ch.dp;
    }
    if (ch.el != null) {
      channel.elevation = ch.el;
    }
    if (ch.az != null) {
      channel.azimuth = ch.az;
    }
    if (ch.dip != null) {
      channel.dip = ch.dip;
    }
  }
  return channel;
}
function markerToEH(mark) {
  let tm = mark.time.toISO();
  tm = tm ? tm : "error";
  const out = {
    tm,
    n: mark.name,
    mtype: mark.markertype,
    desc: mark.description
  };
  return out;
}
function markerTypeFromEH(mtype) {
  if (mtype === "pk" || mtype === "pick") {
    return "pick";
  }
  if (mtype === "md" || mtype === "predicted") {
    return "predicted";
  }
  return mtype;
}
function ehToMarkers(exHead) {
  const bag = extractBagEH(exHead);
  const markList = bag?.mark;
  if (markList != null) {
    return markList.map((m) => {
      return {
        time: isoToDateTime(m.tm),
        name: m.n,
        markertype: m.mtype == null ? "unknown" : markerTypeFromEH(m.mtype),
        description: m.desc == null ? "" : m.desc
      };
    });
  }
  return [];
}
function extractBagEH(jsonEH) {
  if (!jsonEH || typeof jsonEH !== "object") {
    return null;
  }
  const eh = jsonEH;
  if (typeof eh.bag != "object") {
    return null;
  }
  const object2 = eh.bag;
  if (isValidBagJsonEHType(object2)) {
    return object2;
  } else {
    throw new TypeError(`Oops, we did not get Bag extra header JSON!`);
  }
}
function createBagEH() {
  const object2 = {};
  if (isValidBagJsonEHType(object2)) {
    return object2;
  } else {
    throw new TypeError(`Oops, we did not get Bag extra header JSON!`);
  }
}
function isValidBagChannelJsonEHType(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  const answer = typeof object2.la === "number" && typeof object2.lo === "number" && (typeof object2.code === "undefined" || typeof object2.code === "string") && (typeof object2.el === "undefined" || typeof object2.el === "number") && (typeof object2.dp === "undefined" || typeof object2.dp === "number");
  return answer;
}
function isValidBagEventJsonEHType(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  return (typeof object2.id === "undefined" || typeof object2.id === "string") && (typeof object2.or === "undefined" || isValidBagOriginJsonEHType(object2.or)) && (typeof object2.mag === "undefined" || isValidBagMagJsonEHType(object2.mag)) && (typeof object2.mt === "undefined" || typeof object2.mt === "object");
}
function isValidBagOriginJsonEHType(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  return typeof object2.la === "number" && typeof object2.lo === "number" && typeof object2.dp === "number" && typeof object2.tm === "string";
}
function isValidBagMagJsonEHType(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  return (typeof object2.v === "undefined" || typeof object2.v === "number") && (typeof object2.t === "undefined" || typeof object2.t === "string");
}
function isValidBagPathJsonEHType(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  return (typeof object2.gcarc === "undefined" || typeof object2.gcarc === "number") && (typeof object2.az === "undefined" || typeof object2.az === "number") && (typeof object2.baz === "undefined" || typeof object2.baz === "number");
}
function isValidBagMarkJsonEHType(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  return typeof object2.n === "string" && typeof object2.tm === "string" && (typeof object2.mtype === "undefined" || typeof object2.mtype === "string") && (typeof object2.desc === "undefined" || typeof object2.desc === "string");
}
function isValidBagTimeseriesJsonEHType(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  return typeof object2.si === "string" && (typeof object2.proc === "undefined" || typeof object2.proc === "string");
}
function isValidBagJsonEHType(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  if (!((typeof object2.st === "undefined" || isValidBagChannelJsonEHType(object2.st)) && (typeof object2.ev === "undefined" || isValidBagEventJsonEHType(object2.ev)) && (typeof object2.path === "undefined" || isValidBagPathJsonEHType(object2.path)) && (typeof object2.y === "undefined" || typeof object2.y === "object") && (typeof object2.mark === "undefined" || Array.isArray(object2.mark)))) {
    return false;
  }
  const markerList = object2.mark;
  if (!(typeof markerList === "undefined" || Array.isArray(markerList))) {
    return false;
  } else {
    if (markerList != null) {
      for (const m of markerList) {
        if (!isValidBagMarkJsonEHType(m)) {
          return false;
        }
      }
    }
  }
  return true;
}

// src/mseed3.mts
var MINISEED_THREE_MIME = "application/vnd.fdsn.mseed3";
var UNKNOWN_DATA_VERSION = 0;
var CRC_OFFSET = 28;
var FIXED_HEADER_SIZE = 40;
var FDSN_PREFIX2 = "FDSN";
var LITTLE_ENDIAN = true;
var BIG_ENDIAN = false;
function toMSeed3(seis, extraHeaders) {
  const out = new Array(0);
  if (!isDef(extraHeaders)) {
    extraHeaders = {};
  }
  for (const seg of seis.segments) {
    const header = new MSeed3Header();
    let rawData;
    let encoding;
    if (seg.isEncoded()) {
      const encoded = seg.getEncoded();
      if (encoded.length === 1) {
        rawData = encoded[0].dataView;
        encoding = encoded[0].compressionType;
      } else {
        const encodeTypeSet = /* @__PURE__ */ new Set();
        encoded.forEach((cur) => {
          encodeTypeSet.add(cur.compressionType);
        });
        const encodeTypes = Array.from(encodeTypeSet.values());
        if (encodeTypes.length > 1) {
          throw new Error(
            `more than one encoding type in seis segment: ${encodeTypes.length}`
          );
        } else if (encodeTypes.length === 0) {
          throw new Error(`zero encoding type in seis segment`);
        } else if (!encodeTypes[0]) {
          throw new Error(`only encoding type is undef`);
        }
        encoding = encodeTypes[0];
        if (!encoding) {
          throw new Error(`encoding is undefined`);
        }
        if (encoding === INTEGER || encoding === FLOAT || encoding === DOUBLE || encoding === STEIM1 || encoding === STEIM2) {
          const totSize = encoded.reduce(
            (acc, cur) => acc + cur.dataView.byteLength,
            0
          );
          const combined = new Uint8Array(totSize);
          encoded.reduce((offset2, cur) => {
            combined.set(
              new Uint8Array(
                cur.dataView.buffer,
                cur.dataView.byteOffset,
                cur.dataView.byteLength
              ),
              offset2
            );
            return offset2 + cur.dataView.byteLength;
          }, 0);
          rawData = new DataView(combined.buffer);
          if (encoding === STEIM1 || encoding === STEIM2) {
            rawData.setUint32(
              8,
              encoded[encoded.length - 1].dataView.getUint32(8)
            );
          }
        } else {
          throw new Error(
            `Encoding type not steim 1 or 2 or primitive in seis segment: ${encoding}`
          );
        }
      }
    } else {
      rawData = new DataView(seg.y.buffer);
      if (seg.y instanceof Float32Array) {
        encoding = FLOAT;
      } else if (seg.y instanceof Int32Array) {
        encoding = INTEGER;
      } else if (seg.y instanceof Float64Array) {
        encoding = DOUBLE;
      } else {
        throw new Error("unable to save data of encoding: ");
      }
    }
    header.setStart(seg.startTime);
    header.encoding = encoding;
    if (seg.sampleRate > 1e-3) {
      header.sampleRateOrPeriod = seg.sampleRate;
    } else {
      header.sampleRateOrPeriod = -1 * seg.samplePeriod;
    }
    header.numSamples = seg.numPoints;
    header.publicationVersion = UNKNOWN_DATA_VERSION;
    const sid = seg.sourceId ? seg.sourceId : FDSNSourceId.createUnknown(seg.sampleRate);
    header.identifier = sid.toString();
    header.identifierLength = header.identifier.length;
    header.extraHeaders = extraHeaders;
    header.dataLength = rawData.byteLength;
    const record2 = new MSeed3Record(header, extraHeaders, rawData);
    record2.calcSize();
    out.push(record2);
  }
  return out;
}
function parseMSeed3Records(arrayBuffer) {
  const dataRecords = [];
  let offset2 = 0;
  while (offset2 < arrayBuffer.byteLength) {
    if (offset2 > arrayBuffer.byteLength - FIXED_HEADER_SIZE) {
      throw new Error(
        `Not enough bytes left for header, ${arrayBuffer.byteLength - offset2} at offset=${offset2}`
      );
    }
    const dataView = new DataView(arrayBuffer, offset2);
    if (!(dataView.getUint8(0) === 77 && dataView.getUint8(1) === 83)) {
      throw new Error(
        `First byte must be M=77 S=83 at offset=${offset2}, but was ${dataView.getUint8(
          0
        )} ${dataView.getUint8(1)}`
      );
    }
    const dr = MSeed3Record.parseSingleDataRecord(dataView);
    dataRecords.push(dr);
    offset2 += dr.getSize();
  }
  return dataRecords;
}
function mightBeMSeed3Records(arrayBuffer) {
  const dataView = new DataView(arrayBuffer);
  if (!(dataView.getUint8(0) === 77 && dataView.getUint8(1) === 83)) {
    return false;
  }
  const header = MSeed3Header.createFromDataView(dataView);
  if (header.formatVersion !== 3) {
    return false;
  }
  if (header.year < 1900 || header.year > 2500) {
    return false;
  }
  if (header.dayOfYear <= 0 || header.dayOfYear > 366) {
    return false;
  }
  if (header.hour <= 0 || header.hour > 24) {
    return false;
  }
  return true;
}
var MSeed3Record = class _MSeed3Record {
  constructor(header, extraHeaders, rawData) {
    this.header = header;
    this.rawData = rawData;
    this.extraHeaders = extraHeaders;
  }
  /**
   * Parses an miniseed3 data record from a DataView.
   *
   * @param   dataView bytes to parse
   * @returns parsed record
   */
  static parseSingleDataRecord(dataView) {
    const header = MSeed3Header.createFromDataView(dataView);
    const ehoffset = header.getSize();
    const dataoffset = header.getSize() + header.extraHeadersLength;
    const extraDataView = new DataView(
      dataView.buffer,
      dataView.byteOffset + ehoffset,
      header.extraHeadersLength
    );
    const extraHeaders = parseExtraHeaders(extraDataView);
    const sliceStart = dataView.byteOffset + dataoffset;
    const rawData = new DataView(
      dataView.buffer.slice(sliceStart, sliceStart + header.dataLength)
    );
    const xr = new _MSeed3Record(header, extraHeaders, rawData);
    return xr;
  }
  /**
   * Calculates the byte size of the miniseed3 record to hold this data.
   * This should be called if the size is needed after modification
   * of the extraHeaders.
   *
   * @returns size in bytes
   */
  calcSize() {
    const json2 = JSON.stringify(this.extraHeaders);
    if (json2.length > 2) {
      this.header.extraHeadersLength = json2.length;
    } else {
      this.header.extraHeadersLength = 0;
    }
    return this.getSize();
  }
  /**
   * Gets the byte size of the miniseed3 record to hold this data.
   * Note that unless calcSize() has been called, this may not
   * take into account modifications to the extra headers.
   *
   * @returns size in bytes
   */
  getSize() {
    return this.header.getSize() + this.header.extraHeadersLength + this.header.dataLength;
  }
  /**
   * Decompresses the data , if the compression
   *  type is known
   *
   * @returns decompressed data as a typed array, usually Int32Array or Float32Array
   */
  decompress() {
    return this.asEncodedDataSegment().decode();
  }
  /**
   * Wraps data in an EncodedDataSegment for future decompression.
   *
   * @returns waveform data
   */
  asEncodedDataSegment() {
    let swapBytes = LITTLE_ENDIAN;
    if (this.header.encoding === 10 || this.header.encoding === 11 || this.header.encoding === 19) {
      swapBytes = BIG_ENDIAN;
    }
    return new EncodedDataSegment(
      this.header.encoding,
      this.rawData,
      this.header.numSamples,
      swapBytes
    );
  }
  /**
   * Just the header.identifier, included as codes() for compatiblility
   * with parsed miniseed2 data records.
   *
   * @returns string identifier
   */
  codes() {
    return this.header.identifier;
  }
  /**
   * Parses the identifier into an FDSNSourceId.
   *
   * @returns header identifier as source id
   */
  getSourceId() {
    return FDSNSourceId.parse(this.header.identifier);
  }
  /**
   * Saves miniseed3 record into a DataView, recalculating crc.
   *
   * @param   dataView DataView to save into, must be large enough to hold the record.
   * @returns the number of bytes written to the DataView, can be used as offset
   * for writting the next record.
   */
  save(dataView) {
    const json2 = JSON.stringify(this.extraHeaders);
    if (json2.length > 2) {
      this.header.extraHeadersLength = json2.length;
    } else {
      this.header.extraHeadersLength = 0;
    }
    let offset2 = this.header.save(dataView, 0, true);
    if (json2.length > 2) {
      for (let i = 0; i < json2.length; i++) {
        dataView.setInt8(offset2, json2.charCodeAt(i));
        offset2++;
      }
    }
    if (this.rawData !== null) {
      for (let i = 0; i < this.rawData.byteLength; i++) {
        dataView.setUint8(offset2 + i, this.rawData.getUint8(i));
      }
      offset2 += this.rawData.byteLength;
    } else {
      throw new Error("rawData is null");
    }
    const dvcrc = dataView.getUint32(CRC_OFFSET, true);
    if (dvcrc !== 0) {
      throw new Error(`CRC is not zero before calculate! ${dvcrc}`);
    }
    const crc = calculateCRC32C(dataView.buffer);
    dataView.setUint32(CRC_OFFSET, crc, true);
    return offset2;
  }
  /**
   * Calculates crc by saving to a DataView, which sets the crc header to zero
   * and then calculates it based on the rest of the record.
   *
   * @returns         crc pulled from saved miniseed3 record
   */
  calcCrc() {
    const size = this.calcSize();
    const buff = new ArrayBuffer(size);
    const dataView = new DataView(buff);
    const offset2 = this.save(dataView);
    if (offset2 !== size) {
      throw new Error(`expect to write ${size} bytes but only ${offset2}`);
    }
    const crc = dataView.getUint32(CRC_OFFSET, true);
    return crc;
  }
  toString() {
    const ehLines = JSON.stringify(this.extraHeaders, null, 2).split("\n");
    const indentLines = ehLines.join("\n          ");
    return `${this.header.toString()}
          extra headers: ${indentLines}`;
  }
};
var MSeed3Header = class _MSeed3Header {
  constructor() {
    this.recordIndicator = "MS";
    this.formatVersion = 3;
    this.flags = 0;
    this.nanosecond = 0;
    this.year = 1970;
    this.dayOfYear = 1;
    this.hour = 0;
    this.minute = 0;
    this.second = 0;
    this.encoding = 3;
    this.sampleRateOrPeriod = 1;
    this.numSamples = 0;
    this.crc = 0;
    this.publicationVersion = UNKNOWN_DATA_VERSION;
    this.identifierLength = 0;
    this.extraHeadersLength = 2;
    this.identifier = "";
    this.extraHeaders = {};
    this.dataLength = 0;
  }
  /**
   * Parses an miniseed3 fixed header from a DataView.
   *
   * @param   dataView bytes to parse
   * @returns parsed header object
   */
  static createFromDataView(dataView) {
    const header = new _MSeed3Header();
    header.recordIndicator = makeString2(dataView, 0, 2);
    if (header.recordIndicator !== "MS") {
      throw new Error(
        "First 2 bytes of record should be MS but found " + header.recordIndicator
      );
    }
    header.formatVersion = dataView.getUint8(2);
    if (header.formatVersion !== 3) {
      throw new Error("Format Version should be 3, " + header.formatVersion);
    }
    header.flags = dataView.getUint8(3);
    const headerLittleEndian = true;
    header.nanosecond = dataView.getInt32(4, headerLittleEndian);
    header.year = dataView.getInt16(8, headerLittleEndian);
    if (checkByteSwap2(header.year)) {
      throw new Error("Looks like wrong byte order, year=" + header.year);
    }
    header.dayOfYear = dataView.getInt16(10, headerLittleEndian);
    header.hour = dataView.getUint8(12);
    header.minute = dataView.getUint8(13);
    header.second = dataView.getUint8(14);
    header.encoding = dataView.getUint8(15);
    header.sampleRateOrPeriod = dataView.getFloat64(16, headerLittleEndian);
    header.numSamples = dataView.getUint32(24, headerLittleEndian);
    header.crc = dataView.getUint32(28, headerLittleEndian);
    header.publicationVersion = dataView.getUint8(32);
    header.identifierLength = dataView.getUint8(33);
    header.extraHeadersLength = dataView.getUint16(34, headerLittleEndian);
    header.dataLength = dataView.getUint32(36, headerLittleEndian);
    header.identifier = makeString2(dataView, 40, header.identifierLength);
    return header;
  }
  get start() {
    return this.startAsDateTime();
  }
  get end() {
    return this.timeOfSample(this.numSamples - 1);
  }
  get sampleRate() {
    if (this.sampleRateOrPeriod < 0) {
      return -1 / this.sampleRateOrPeriod;
    } else {
      return this.sampleRateOrPeriod;
    }
  }
  get samplePeriod() {
    if (this.sampleRateOrPeriod <= 0) {
      return -1 * this.sampleRateOrPeriod;
    } else {
      return 1 / this.sampleRateOrPeriod;
    }
  }
  /**
   * Calculates size of the fixed header including the variable
   * length identifier, but without the extra headers.
   *
   * @returns size in bytes of fixed header
   */
  getSize() {
    return FIXED_HEADER_SIZE + this.identifier.length;
  }
  encodingName() {
    let encode_name = "unknown";
    if (this.encoding === 0) {
      encode_name = "Text";
    } else if (this.encoding === 1) {
      encode_name = "16-bit integer";
    } else if (this.encoding === 3) {
      encode_name = "32-bit integer";
    } else if (this.encoding === 4) {
      encode_name = "32-bit float";
    } else if (this.encoding === 5) {
      encode_name = "64-bit float";
    } else if (this.encoding === 11) {
      encode_name = "STEIM-2 integer compression";
    } else if (this.encoding === 10) {
      encode_name = "STEIM-1 integer compression";
    } else if (this.encoding === 19) {
      encode_name = "STEIM-3 integer compression";
    } else if (this.encoding === 100) {
      encode_name = "Opaque data";
    }
    return encode_name;
  }
  /**
   * Text representation of the miniseed3 header. This is modeled after
   * the output of mseed3-text from the mseed3-utils package from IRIS.
   *
   * @returns textual repersentation
   */
  toString() {
    const encode_name = this.encodingName();
    let bitFlagStr = "";
    if (this.flags & 1) {
      bitFlagStr = `${bitFlagStr}
                         [Bit 0] Calibration signals present`;
    }
    if (this.flags & 2) {
      bitFlagStr = `${bitFlagStr}
                         [Bit 1] Time tag is questionable`;
    }
    if (this.flags & 4) {
      bitFlagStr = `${bitFlagStr}
                         [Bit 2] Clock locked`;
    }
    if (this.flags & 8) {
      bitFlagStr = `${bitFlagStr}
                         [Bit 3] Undefined bit set`;
    }
    if (this.flags & 16) {
      bitFlagStr = `${bitFlagStr}
                         [Bit 4] Undefined bit set`;
    }
    if (this.flags & 32) {
      bitFlagStr = `${bitFlagStr}
                         [Bit 5] Undefined bit set`;
    }
    if (this.flags & 64) {
      bitFlagStr = `${bitFlagStr}
                         [Bit 6] Undefined bit set`;
    }
    if (this.flags & 128) {
      bitFlagStr = `${bitFlagStr}
                         [Bit 7] Undefined bit set`;
    }
    return `${this.identifier}, version ${this.publicationVersion}, ${this.getSize() + this.dataLength + this.extraHeadersLength} bytes (format: ${this.formatVersion})
             start time: ${this.getStartFieldsAsISO()} (${padZeros(this.dayOfYear, 3)})
      number of samples: ${this.numSamples}
       sample rate (Hz): ${this.sampleRate}
                  flags: [${(this.flags >>> 0).toString(2).padStart(8, "0")}] 8 bits${bitFlagStr}
                    CRC: ${crcToHexString(this.crc)}
    extra header length: ${this.extraHeadersLength} bytes
    data payload length: ${this.dataLength} bytes
       payload encoding: ${encode_name} (val: ${this.encoding})`;
  }
  /**
   * Start time in the format output by mseed3-utils from IRIS. Format is
   * yyyy,ooo,HH:mm:ss.SSSSSS
   *
   * @returns start time
   */
  startFieldsInUtilFormat() {
    return `${this.year},${padZeros(this.dayOfYear, 3)},${padZeros(this.hour, 2)}:${padZeros(this.minute, 2)}:${padZeros(this.second, 2)}.${padZeros(Math.floor(this.nanosecond / 1e3), 6)}`;
  }
  /**
   * Converts start time header fields to ISO8601 time string. This will include
   * factional seconds to nanosecond precision.
   *
   * @param trimMicroNano trim to microsecond precision if nanos are 000
   * @returns iso start time
   */
  getStartFieldsAsISO(trimMicroNano = true) {
    const d = this.startAsDateTime().set({ millisecond: 0 }).toISO({ includeOffset: false, suppressMilliseconds: true });
    let fracSec;
    if (trimMicroNano && this.nanosecond % 1e3 === 0) {
      fracSec = padZeros(this.nanosecond / 1e3, 6);
    } else {
      fracSec = padZeros(this.nanosecond, 9);
    }
    return `${d}.${fracSec}Z`;
  }
  /**
   * sets start time headers.
   *
   * @param starttime start as DateTime
   */
  setStart(starttime) {
    this.nanosecond = starttime.millisecond * 1e6;
    this.year = starttime.year;
    this.dayOfYear = starttime.ordinal;
    this.hour = starttime.hour;
    this.minute = starttime.minute;
    this.second = starttime.second;
  }
  /**
   * Calculates time of the ith sample.
   *
   * @param   i sample number
   * @returns the time
   */
  timeOfSample(i) {
    return this.start.plus(Duration.fromMillis(1e3 * i / this.sampleRate));
  }
  /**
   * Writes to the given dataview.
   *
   * @param   dataView write buffer
   * @param   offset   offset within the buffer
   * @param   zeroCrc  optionally zero out the crc field in order to recalculate
   * @returns          new offset after this record
   */
  save(dataView, offset2 = 0, zeroCrc = false) {
    dataView.setUint8(offset2, this.recordIndicator.charCodeAt(0));
    offset2++;
    dataView.setUint8(offset2, this.recordIndicator.charCodeAt(1));
    offset2++;
    dataView.setUint8(offset2, this.formatVersion);
    offset2++;
    dataView.setUint8(offset2, this.flags);
    offset2++;
    dataView.setUint32(offset2, this.nanosecond, true);
    offset2 += 4;
    dataView.setUint16(offset2, this.year, true);
    offset2 += 2;
    dataView.setUint16(offset2, this.dayOfYear, true);
    offset2 += 2;
    dataView.setUint8(offset2, this.hour);
    offset2++;
    dataView.setUint8(offset2, this.minute);
    offset2++;
    dataView.setUint8(offset2, this.second);
    offset2++;
    dataView.setUint8(offset2, this.encoding);
    offset2++;
    dataView.setFloat64(offset2, this.sampleRateOrPeriod, true);
    offset2 += 8;
    dataView.setUint32(offset2, this.numSamples, true);
    offset2 += 4;
    if (zeroCrc) {
      dataView.setUint32(offset2, 0, true);
    } else {
      dataView.setUint32(offset2, this.crc, true);
    }
    offset2 += 4;
    dataView.setUint8(offset2, this.publicationVersion);
    offset2++;
    dataView.setUint8(offset2, this.identifier.length);
    offset2++;
    dataView.setUint16(offset2, this.extraHeadersLength, true);
    offset2 += 2;
    dataView.setUint32(offset2, this.dataLength, true);
    offset2 += 4;
    for (let i = 0; i < this.identifier.length; i++) {
      dataView.setUint8(offset2, this.identifier.charCodeAt(i));
      offset2++;
    }
    return offset2;
  }
  /**
   * Converts header start time to DateTime
   *
   * @returns         start time as DateTime
   */
  startAsDateTime() {
    const millis = Math.round(this.nanosecond / 1e6);
    let d = DateTime.fromObject(
      {
        year: this.year,
        ordinal: this.dayOfYear,
        hour: this.hour,
        minute: this.minute,
        second: this.second,
        millisecond: 0
      },
      UTC_OPTIONS
    );
    d = d.plus(millis);
    if (!d.isValid) {
      throw new Error(`Start is invalid: ${this.startFieldsInUtilFormat()} ${d.invalidReason} ${d.invalidExplanation}`);
    }
    return d;
  }
};
function parseExtraHeaders(dataView) {
  if (dataView.byteLength === 0) {
    return {};
  }
  const firstChar = dataView.getUint8(0);
  if (firstChar === 123) {
    const jsonStr = makeString2(dataView, 0, dataView.byteLength);
    const v = JSON.parse(jsonStr);
    if (typeof v === "object") {
      return v;
    } else {
      throw new Error(
        `extra headers does not look like JSON object: ${jsonStr}"`
      );
    }
  } else {
    throw new Error(
      "do not understand extras with first char val: " + firstChar + " " + (firstChar === 123)
    );
  }
}
function padZeros(val, len) {
  let out = "" + val;
  while (out.length < len) {
    out = "0" + out;
  }
  return out;
}
function makeString2(dataView, offset2, length) {
  const utf8decoder = new TextDecoder("utf-8");
  const u8arr = new Uint8Array(
    dataView.buffer,
    dataView.byteOffset + offset2,
    length
  );
  return utf8decoder.decode(u8arr).trim();
}
function checkByteSwap2(year) {
  return year < 1960 || year > 2055;
}
function areContiguous2(dr1, dr2, sampRatio = 1.5) {
  const h1 = dr1.header;
  const h2 = dr2.header;
  return h1.end < h2.start && h1.end.plus(Duration.fromMillis(1e3 * sampRatio / h1.sampleRate)) >= h2.start;
}
function createSeismogramSegment2(contig) {
  if (!Array.isArray(contig)) {
    contig = [contig];
  }
  const contigData = contig.map((dr) => dr.asEncodedDataSegment());
  const out = new SeismogramSegment(
    contigData,
    contig[0].header.sampleRate,
    contig[0].header.start,
    contig[0].getSourceId()
  );
  const bag = extractBagEH(contig[0].extraHeaders);
  if (bag?.y?.si) {
    out.yUnit = bag?.y?.si;
  }
  return out;
}
function merge2(drList) {
  return new Seismogram(mergeSegments2(drList));
}
function mergeSegments2(drList) {
  const out = [];
  let currDR;
  drList.sort(function(a, b) {
    return a.header.start.valueOf() - b.header.start.valueOf();
  });
  let contig = [];
  for (let i = 0; i < drList.length; i++) {
    currDR = drList[i];
    if (contig.length === 0) {
      contig.push(currDR);
    } else if (areContiguous2(contig[contig.length - 1], currDR)) {
      contig.push(currDR);
    } else {
      out.push(createSeismogramSegment2(contig));
      contig = [currDR];
    }
  }
  if (contig.length > 0) {
    out.push(createSeismogramSegment2(contig));
  }
  return out;
}
function byChannel2(drList) {
  const out = /* @__PURE__ */ new Map();
  let key;
  for (let i = 0; i < drList.length; i++) {
    const currDR = drList[i];
    key = currDR.codes();
    let drArray = out.get(key);
    if (!drArray) {
      drArray = [currDR];
      out.set(key, drArray);
    } else {
      drArray.push(currDR);
    }
  }
  return out;
}
function seismogramSegmentPerChannel2(drList) {
  let out = new Array(0);
  const byChannelMap = byChannel2(drList);
  byChannelMap.forEach(
    (segments) => out = out.concat(mergeSegments2(segments))
  );
  return out;
}
function seismogramPerChannel2(drList) {
  const out = [];
  const byChannelMap = byChannel2(drList);
  byChannelMap.forEach((segments) => out.push(merge2(segments)));
  return out;
}
function sddPerChannel(drList) {
  const out = [];
  const byChannelMap = byChannel2(drList);
  byChannelMap.forEach((segments) => {
    const sdd = SeismogramDisplayData.fromSeismogram(merge2(segments));
    out.push(sdd);
    segments.forEach((seg) => {
      const q = ehToQuake(seg.extraHeaders);
      if (q != null) {
        sdd.addQuake(q);
      }
      const c = ehToChannel(seg.extraHeaders, seg.getSourceId());
      if (c != null) {
        sdd.channel = c;
      }
      const marks = ehToMarkers(seg.extraHeaders);
      marks.forEach((mark) => sdd.addMarker(mark));
    });
  });
  return out;
}
function convertMS2toMSeed3(mseed2) {
  const out = [];
  for (let i = 0; i < mseed2.length; i++) {
    out.push(convertMS2Record(mseed2[i]));
  }
  return out;
}
function convertMS2Record(ms2record) {
  const xHeader = new MSeed3Header();
  const xExtras = {};
  const ms2H = ms2record.header;
  xHeader.flags = (ms2H.activityFlags & 1) * 2 + (ms2H.ioClockFlags & 64) * 4 + (ms2H.dataQualityFlags & 16) * 8;
  xHeader.year = ms2H.startBTime.year;
  xHeader.dayOfYear = ms2H.startBTime.jday;
  xHeader.hour = ms2H.startBTime.hour;
  xHeader.minute = ms2H.startBTime.min;
  xHeader.second = ms2H.startBTime.sec;
  xHeader.nanosecond = ms2H.startBTime.tenthMilli * 1e5 + ms2H.startBTime.microsecond * 1e3;
  xHeader.sampleRateOrPeriod = ms2H.sampleRate >= 1 ? ms2H.sampleRate : -1 / ms2H.sampleRate;
  xHeader.encoding = ms2record.header.encoding;
  xHeader.publicationVersion = UNKNOWN_DATA_VERSION;
  xHeader.dataLength = ms2record.data.byteLength;
  const sid = FDSNSourceId.fromNslc(ms2H.netCode, ms2H.staCode, ms2H.locCode ? ms2H.locCode : "", ms2H.chanCode);
  xHeader.identifier = sid.toString();
  xHeader.identifierLength = xHeader.identifier.length;
  xHeader.numSamples = ms2H.numSamples;
  xHeader.crc = 0;
  if (ms2H.typeCode) {
    if (ms2H.typeCode === R_TYPECODE) {
      xHeader.publicationVersion = 1;
    } else if (ms2H.typeCode === D_TYPECODE) {
      xHeader.publicationVersion = 2;
    } else if (ms2H.typeCode === Q_TYPECODE) {
      xHeader.publicationVersion = 3;
    } else if (ms2H.typeCode === M_TYPECODE) {
      xHeader.publicationVersion = 4;
    }
    if (ms2H.typeCode !== D_TYPECODE) {
      xExtras.DataQuality = ms2H.typeCode;
    }
  }
  if (xHeader.nanosecond < 0) {
    xHeader.second -= 1;
    xHeader.nanosecond += 1e9;
    if (xHeader.second < 0) {
      xHeader.second += 60;
      xHeader.minute -= 1;
      if (xHeader.minute < 0) {
        xHeader.minute += 60;
        xHeader.hour -= 1;
        if (xHeader.hour < 0) {
          xHeader.hour += 24;
          xHeader.dayOfYear = -1;
          if (xHeader.dayOfYear < 0) {
            xHeader.dayOfYear += 365;
            xHeader.year -= 1;
          }
        }
      }
    }
  }
  xHeader.extraHeadersLength = JSON.stringify(xExtras).length;
  let data;
  if (ms2record.header.encoding === 11 || ms2record.header.encoding === 12 || ms2record.header.encoding <= 5 && ms2record.header.littleEndian) {
    data = ms2record.data;
  } else {
    data = ms2record.decompress();
    if (data instanceof Float32Array) {
      xHeader.encoding = FLOAT;
    } else if (data instanceof Int32Array) {
      xHeader.encoding = INTEGER;
    } else {
      xHeader.encoding = DOUBLE;
    }
  }
  const out = new MSeed3Record(xHeader, xExtras, new DataView(data.buffer));
  return out;
}
var kCRCTable = new Int32Array([
  0,
  4067132163,
  3778769143,
  324072436,
  3348797215,
  904991772,
  648144872,
  3570033899,
  2329499855,
  2024987596,
  1809983544,
  2575936315,
  1296289744,
  3207089363,
  2893594407,
  1578318884,
  274646895,
  3795141740,
  4049975192,
  51262619,
  3619967088,
  632279923,
  922689671,
  3298075524,
  2592579488,
  1760304291,
  2075979607,
  2312596564,
  1562183871,
  2943781820,
  3156637768,
  1313733451,
  549293790,
  3537243613,
  3246849577,
  871202090,
  3878099393,
  357341890,
  102525238,
  4101499445,
  2858735121,
  1477399826,
  1264559846,
  3107202533,
  1845379342,
  2677391885,
  2361733625,
  2125378298,
  820201905,
  3263744690,
  3520608582,
  598981189,
  4151959214,
  85089709,
  373468761,
  3827903834,
  3124367742,
  1213305469,
  1526817161,
  2842354314,
  2107672161,
  2412447074,
  2627466902,
  1861252501,
  1098587580,
  3004210879,
  2688576843,
  1378610760,
  2262928035,
  1955203488,
  1742404180,
  2511436119,
  3416409459,
  969524848,
  714683780,
  3639785095,
  205050476,
  4266873199,
  3976438427,
  526918040,
  1361435347,
  2739821008,
  2954799652,
  1114974503,
  2529119692,
  1691668175,
  2005155131,
  2247081528,
  3690758684,
  697762079,
  986182379,
  3366744552,
  476452099,
  3993867776,
  4250756596,
  255256311,
  1640403810,
  2477592673,
  2164122517,
  1922457750,
  2791048317,
  1412925310,
  1197962378,
  3037525897,
  3944729517,
  427051182,
  170179418,
  4165941337,
  746937522,
  3740196785,
  3451792453,
  1070968646,
  1905808397,
  2213795598,
  2426610938,
  1657317369,
  3053634322,
  1147748369,
  1463399397,
  2773627110,
  4215344322,
  153784257,
  444234805,
  3893493558,
  1021025245,
  3467647198,
  3722505002,
  797665321,
  2197175160,
  1889384571,
  1674398607,
  2443626636,
  1164749927,
  3070701412,
  2757221520,
  1446797203,
  137323447,
  4198817972,
  3910406976,
  461344835,
  3484808360,
  1037989803,
  781091935,
  3705997148,
  2460548119,
  1623424788,
  1939049696,
  2180517859,
  1429367560,
  2807687179,
  3020495871,
  1180866812,
  410100952,
  3927582683,
  4182430767,
  186734380,
  3756733383,
  763408580,
  1053836080,
  3434856499,
  2722870694,
  1344288421,
  1131464017,
  2971354706,
  1708204729,
  2545590714,
  2229949006,
  1988219213,
  680717673,
  3673779818,
  3383336350,
  1002577565,
  4010310262,
  493091189,
  238226049,
  4233660802,
  2987750089,
  1082061258,
  1395524158,
  2705686845,
  1972364758,
  2279892693,
  2494862625,
  1725896226,
  952904198,
  3399985413,
  3656866545,
  731699698,
  4283874585,
  222117402,
  510512622,
  3959836397,
  3280807620,
  837199303,
  582374963,
  3504198960,
  68661723,
  4135334616,
  3844915500,
  390545967,
  1230274059,
  3141532936,
  2825850620,
  1510247935,
  2395924756,
  2091215383,
  1878366691,
  2644384480,
  3553878443,
  565732008,
  854102364,
  3229815391,
  340358836,
  3861050807,
  4117890627,
  119113024,
  1493875044,
  2875275879,
  3090270611,
  1247431312,
  2660249211,
  1828433272,
  2141937292,
  2378227087,
  3811616794,
  291187481,
  34330861,
  4032846830,
  615137029,
  3603020806,
  3314634738,
  939183345,
  1776939221,
  2609017814,
  2295496738,
  2058945313,
  2926798794,
  1545135305,
  1330124605,
  3173225534,
  4084100981,
  17165430,
  307568514,
  3762199681,
  888469610,
  3332340585,
  3587147933,
  665062302,
  2042050490,
  2346497209,
  2559330125,
  1793573966,
  3190661285,
  1279665062,
  1595330642,
  2910671697
]);
function calculateCRC32C(buf, initial = 0) {
  let ubuf;
  if (buf instanceof ArrayBuffer || buf instanceof SharedArrayBuffer) {
    ubuf = new Uint8Array(buf);
  } else if (buf instanceof Uint8Array) {
    ubuf = buf;
  } else {
    throw new Error("arg must be ArrayBufferLike or Uint8Array");
  }
  let crc = (initial | 0) ^ -1;
  for (let i = 0; i < ubuf.length; i++) {
    crc = kCRCTable[(crc ^ ubuf[i]) & 255] ^ crc >>> 8;
  }
  return (crc ^ -1) >>> 0;
}
function crcToHexString(crc) {
  if (crc < 0) {
    crc = 4294967295 + crc + 1;
  }
  const s2 = crc.toString(16).toUpperCase();
  return "0x" + s2;
}

// src/datalink.mts
var WS_DATALINK_SUBPROTOCOL = "DataLink1.1";
var MODE = /* @__PURE__ */ ((MODE2) => {
  MODE2["Query"] = "QUERY";
  MODE2["Stream"] = "STREAM";
  return MODE2;
})(MODE || {});
var QUERY_MODE = "QUERY" /* Query */;
var STREAM_MODE = "STREAM" /* Stream */;
var MAX_PROC_NUM = Math.pow(2, 16) - 2;
var USER_BROWSER = "browser";
var DEFAULT_PROGRAM = "seisplotjs";
var DEFAULT_ARCH = "javascript";
var ERROR = "ERROR";
var OK = "OK";
var INFO = "INFO";
var ID = "ID";
var PACKET = "PACKET";
var STREAM = "STREAM";
var ENDSTREAM = "ENDSTREAM";
var MSEED_TYPE = "/MSEED";
var MSEED3_TYPE = "/MSEED3";
var JSON_TYPE = "/JSON";
var EARTHSCOPE_RINGSERVER_URL = "wss://rtserve.earthscope.org/datalink";
var IRIS_RINGSERVER_URL = EARTHSCOPE_RINGSERVER_URL;
function extractDLProto(lines) {
  for (let line of lines) {
    line = line.trim();
    const items = line.split(/[ ,]+/);
    for (const p of items) {
      if (p.startsWith("DLPROTO:")) {
        return p.substring(8);
      }
    }
  }
  return "1.0";
}
var defaultHandleResponse = function(dlResponse) {
  log(`Unhandled datalink response: ${dlResponse.toString()}`);
};
var DataLinkConnection = class _DataLinkConnection {
  constructor(url2, packetHandler, errorHandler) {
    this.dlproto = "1.0";
    this.webSocket = null;
    this.subprotocol = WS_DATALINK_SUBPROTOCOL;
    this.url = url2 ? url2 : EARTHSCOPE_RINGSERVER_URL;
    this._mode = "QUERY" /* Query */;
    this.packetHandler = packetHandler;
    this.errorHandler = errorHandler;
    this.logCommandFn = (msg) => {
    };
    this.closeHandler = null;
    this.serverId = null;
    this.clientIdNum = Math.floor(Math.random() * MAX_PROC_NUM) + 1;
    this.programname = DEFAULT_PROGRAM;
    this.username = USER_BROWSER;
    this.architecture = DEFAULT_ARCH;
    this._responseResolve = null;
    this._responseReject = null;
  }
  /**
   * Set a callback function called when the connection is closed.
   *
   * @param  closeHandler callback function
   */
  setOnClose(closeHandler) {
    this.closeHandler = closeHandler;
  }
  /**
   * creates the websocket connection and sends the client ID.
   *
   *  @returns a Promise that resolves to the server's ID.
   */
  connect() {
    if (this.webSocket) {
      this.webSocket.close();
      this.webSocket = null;
    }
    return new Promise((resolve, reject) => {
      if (this.webSocket) {
        this.webSocket.close();
      }
      const webSocket = new WebSocket(this.url, this.subprotocol);
      this.webSocket = webSocket;
      webSocket.binaryType = "arraybuffer";
      webSocket.onmessage = (event) => {
        this.handle(event);
      };
      webSocket.onerror = (event) => {
        const evtError = toError(event);
        this.handleError(evtError);
        reject(evtError);
      };
      webSocket.onclose = (closeEvent) => {
        this.webSocket = null;
        this._mode = "QUERY" /* Query */;
        if (this.closeHandler) {
          this.closeHandler(closeEvent);
        }
      };
      webSocket.onopen = () => {
        resolve(this);
      };
    }).then((datalink) => {
      return datalink.sendId();
    }).catch((e) => {
      if (!this.webSocket?.protocol || this.webSocket.protocol.length === 0) {
        throw new Error(`fail to create websocket, possible due to subprotocol: sent subprotocol=${this.subprotocol} received empty`);
      }
      throw e;
    }).then((idmsg) => {
      this.serverId = idmsg;
      return idmsg;
    });
  }
  /**
   * @returns true if the websocket is connected (non-null)
   */
  isConnected() {
    return this.webSocket !== null;
  }
  /**
   * @returns the current mode, QUERY_MODE or STREAM_MODE
   */
  get mode() {
    return this._mode;
  }
  /**
   * Switches to streaming mode to receive data packets from the ringserver.
   *
   * @returns promise to the response
   */
  stream() {
    this._mode = "STREAM" /* Stream */;
    return this.awaitDLCommand(STREAM, "").then(
      (dlResponse) => _DataLinkConnection.ensureDataLinkResponse(dlResponse)
    ).then((dlResp) => {
      if (this.logCommandFn) {
        this.logCommandFn(dlResp.message);
      }
      return dlResp;
    });
  }
  /**
   * Switches back to query mode to enable commands to be sent to the ringserver.
   */
  endStream() {
    if (this.webSocket === null || this._mode === null || this._mode === "QUERY" /* Query */) {
      return;
    }
    this._mode = "QUERY" /* Query */;
    this.sendDLCommand(ENDSTREAM, "");
  }
  /**
   * Closes the connection and the underlying websocket. No communication
   * is possible until connect() is called again.
   */
  close() {
    if (this.webSocket) {
      this.endStream();
      if (this.webSocket) {
        this.webSocket.close();
      }
      this.webSocket = null;
      this._mode = "QUERY" /* Query */;
    }
  }
  /**
   * Send a ID Command. Command is a string.
   *
   * @returns a Promise that resolves to the response from the ringserver.
   */
  sendId() {
    return this.id(
      this.programname,
      this.username,
      stringify(this.clientIdNum),
      this.architecture
    ).then(
      (dlResponse) => _DataLinkConnection.ensureDataLinkResponse(dlResponse)
    ).then((dlResp) => {
      if (this.logCommandFn) {
        this.logCommandFn(dlResp.message);
      }
      return dlResp;
    }).then((dlResponse) => {
      if (dlResponse.type === "ID") {
        this.serverId = "" + dlResponse.message;
        const lines = this.serverId.split(/\r?\n/g);
        this.dlproto = extractDLProto(lines);
        return this.serverId;
      } else {
        throw new Error("not ID response: " + stringify(dlResponse.type));
      }
    });
  }
  /**
   * encodes as a Datalink packet, header with optional data section as
   * binary Uint8Array. Size of the binary data is appended
   * to the header if present.
   *
   * @param header the command/header string
   * @param data optional data portion
   * @returns datalink packet as an ArrayBufferLike
   */
  encodeDL(header, data) {
    let cmdLen = header.length;
    let len = 3 + header.length;
    let lenStr = "";
    if (data && data.length > 0) {
      lenStr = String(data.length);
      len += lenStr.length + 1;
      cmdLen += lenStr.length + 1;
      len += data.length;
    }
    const rawPacket = new ArrayBuffer(len);
    const binaryPacket = new Uint8Array(rawPacket);
    const packet = new DataView(rawPacket);
    packet.setUint8(0, 68);
    packet.setUint8(1, 76);
    packet.setUint8(2, cmdLen);
    let i = 3;
    for (const c of header) {
      packet.setUint8(i, c.charCodeAt(0));
      i++;
    }
    const SPACE = " ";
    if (data && data.length > 0) {
      packet.setUint8(i, SPACE.charCodeAt(0));
      i++;
      for (const c of lenStr) {
        packet.setUint8(i, c.charCodeAt(0));
        i++;
      }
      binaryPacket.set(data, i);
    }
    return rawPacket;
  }
  /**
   * sends the header with optional binary data
   * as the data section. Size of the data is appended
   * to the header before sending if present.
   *
   * @param header header to send
   * @param data optional data to send
   */
  sendDLBinary(header, data) {
    const rawPacket = this.encodeDL(header, data);
    if (this.webSocket) {
      this.webSocket.send(rawPacket);
    } else {
      throw new Error("WebSocket has been closed.");
    }
  }
  /**
   * sends the command as header with optional dataString
   * as the data section. Size of the dataString is appended
   * to the header before sending.
   *
   * @param command the command/header string
   * @param dataString optional data portion of packet
   */
  sendDLCommand(command, dataString) {
    this.sendDLBinary(command, stringToUint8Array(dataString));
  }
  /**
   * Send a DataLink Command and await the response. Command is a string.
   *
   * @param header packet header
   * @param data optional data portion of packet
   * @returns a Promise that resolves with the webSocket MessageEvent.
   */
  awaitDLBinary(header, data) {
    const promise2 = new Promise(
      (resolve, reject) => {
        this._responseResolve = resolve;
        this._responseReject = reject;
        this.sendDLBinary(header, data);
      }
    ).then((response) => {
      this._responseResolve = null;
      this._responseReject = null;
      return response;
    }).catch((error51) => {
      this._responseResolve = null;
      this._responseReject = null;
      throw error51;
    });
    return promise2;
  }
  /**
   * Send a DataLink Command and await the response. Command is a string.
   * Returns a Promise that resolves with the webSocket MessageEvent.
   *
   * @param command the command/header string
   * @param dataString optional data portion of packet
   * @returns promise to server's response
   */
  awaitDLCommand(command, dataString) {
    if (this.logCommandFn) {
      this.logCommandFn(`${command} ${dataString != null ? dataString : ""}`);
    }
    return this.awaitDLBinary(command, stringToUint8Array(dataString));
  }
  /**
   * Writes data to the ringserver and awaits a acknowledgement.
   *
   * @param   streamid    stream id for packet header
   * @param   hpdatastart start of timewindow the packet covers
   * @param   hpdataend   end of timewindow the packet covers
   * @param   data        optional data to send
   * @returns             promise to server's response
   */
  writeAck(streamid, hpdatastart, hpdataend, data) {
    const header = `WRITE ${streamid} ${dateTimeToHPTime(
      hpdatastart
    )} ${dateTimeToHPTime(hpdataend)} A`;
    return this.awaitDLBinary(header, data);
  }
  /**
   * Makes sure a response actually is a DataLinkResponse
   *
   * @param   dl datalink packet/response
   * @returns DataLinkResponse after checking instanceof
   * @throws Error if not a DataLinkResponse
   */
  static ensureDataLinkResponse(dl) {
    if (dl instanceof DataLinkResponse) {
      return dl;
    }
    throw new Error(`Expected DataLinkResponse but got ${dl.header}`);
  }
  /**
   * Makes sure a response actually is a DataLinkPacket
   *
   * @param   dl datalink packet/response
   * @returns DataLinkPacket after checking instanceof
   * @throws Error if not a DataLinkPacket
   */
  static ensureDataLinkPacket(dl) {
    if (dl instanceof DataLinkPacket) {
      return dl;
    }
    throw new Error(`Expected DataLinkPacket but got ${dl.type}`);
  }
  /**
   * Send id and await server's response. All of these are can more or less
   * be filled with dummy values. They are mostly used for logging and debugging
   * on the server side.
   *
   * @param programname name of program, ex seisplotjs
   * @param username name of user, ex browser
   * @param processid process number, used to differentiate between multiple running instances
   * @param architecture cpu architecture, ex javascript
   * @returns promise to servers response
   */
  id(programname, username, processid, architecture) {
    const command = `ID ${programname}:${username}:${processid}:${architecture}`;
    return this.awaitDLCommand(command).then(
      (dlResponse) => _DataLinkConnection.ensureDataLinkResponse(dlResponse)
    ).then((dlResp) => {
      if (this.logCommandFn) {
        this.logCommandFn(dlResp.message);
      }
      return dlResp;
    });
  }
  /**
   * Send info command for infoType.
   *
   * @param infoType type to get info for
   * @returns promise to server's response
   */
  info(infoType) {
    const command = `INFO ${infoType}`;
    return this.awaitDLCommand(command).then(
      (dlResponse) => _DataLinkConnection.ensureDataLinkResponse(dlResponse)
    ).then((dlResp) => {
      if (this.logCommandFn) {
        this.logCommandFn(dlResp.message);
      }
      return dlResp;
    });
  }
  infoStatus() {
    return this.info("STATUS").then((daResp) => {
      return StatusResponse.fromDatalinkResponse(daResp);
    });
  }
  infoStreams() {
    return this.info("STREAMS").then((daResp) => {
      return StreamsResponse.fromDatalinkResponse(daResp);
    });
  }
  infoConnections() {
    return this.info("CONNECTIONS").then((daResp) => {
      return ConnectionsResponse.fromDatalinkResponse(daResp);
    });
  }
  /**
   * Send position after command.
   *
   * @param time time to position after
   * @returns promise to server's response
   */
  positionAfter(time3) {
    return this.positionAfterHPTime(dateTimeToHPTime(time3)).then(
      (dlResponse) => _DataLinkConnection.ensureDataLinkResponse(dlResponse)
    ).then((dlResp) => {
      if (this.logCommandFn) {
        this.logCommandFn(dlResp.message);
      }
      return dlResp;
    });
  }
  /**
   * Send position after command.
   *
   * @param hpTime time to position after
   * @returns promise to server's response
   */
  positionAfterHPTime(hpTime) {
    const command = `POSITION AFTER ${hpTime}`;
    return this.awaitDLCommand(command).then(
      (dlResponse) => _DataLinkConnection.ensureDataLinkResponse(dlResponse)
    ).then((dlResp) => {
      if (this.logCommandFn) {
        this.logCommandFn(dlResp.message);
      }
      return dlResp;
    });
  }
  /**
   * Send match command.
   *
   * @param pattern regular expression to match streams
   * @returns promise to server's response
   */
  match(pattern) {
    const command = `MATCH`;
    return this.awaitDLCommand(command, pattern).then(
      (dlResponse) => _DataLinkConnection.ensureDataLinkResponse(dlResponse)
    ).then((dlResp) => {
      if (this.logCommandFn) {
        this.logCommandFn(dlResp.message);
      }
      return dlResp;
    });
  }
  /**
   * Send reject command.
   *
   * @param pattern regular expression to reject streams
   * @returns promise to server's response
   */
  reject(pattern) {
    const command = `REJECT ${pattern}`;
    return this.awaitDLCommand(command).then(
      (dlResponse) => _DataLinkConnection.ensureDataLinkResponse(dlResponse)
    ).then((dlResp) => {
      if (this.logCommandFn) {
        this.logCommandFn(dlResp.message);
      }
      return dlResp;
    });
  }
  /**
   * Read a single packet for the given id.
   *
   * @param packetId id of the packet of interest
   * @returns promise to server's response
   */
  read(packetId) {
    const command = `READ ${packetId}`;
    return this.awaitDLBinary(command).then(
      (dlResponse) => _DataLinkConnection.ensureDataLinkPacket(dlResponse)
    );
  }
  /**
   * Handles a web socket message from the data link connection.
   *
   * @private
   * @param wsEvent web socket event to handle
   */
  handle(wsEvent) {
    const rawData = wsEvent.data;
    if (rawData instanceof ArrayBuffer || rawData instanceof SharedArrayBuffer) {
      this.handleArrayBuffer(rawData);
    }
  }
  handleArrayBuffer(rawData) {
    const dlPreHeader = new DataView(rawData, 0, 3);
    if ("D" === String.fromCharCode(dlPreHeader.getUint8(0)) && "L" === String.fromCharCode(dlPreHeader.getUint8(1))) {
      const headerLen = dlPreHeader.getUint8(2);
      const header = dataViewToString(new DataView(rawData, 3, headerLen));
      if (header.startsWith(PACKET)) {
        const packet = new DataLinkPacket(
          header,
          new DataView(rawData, 3 + headerLen)
        );
        if (this.packetHandler) {
          try {
            this.packetHandler(packet);
          } catch (e) {
            this.handleError(toError(e));
          }
        } else {
          this.handleError(new Error("packetHandler not defined"));
        }
      } else {
        let dv;
        if (rawData.byteLength > 3 + headerLen) {
          dv = new DataView(rawData, 3 + headerLen);
        }
        const dlResponse = DataLinkResponse.parse(header, dv);
        if (dlResponse.type === "ENDSTREAM") {
          this._mode = "QUERY" /* Query */;
        } else {
          if (this._responseResolve) {
            this._responseResolve(dlResponse);
          } else {
            defaultHandleResponse(dlResponse);
          }
        }
      }
    } else {
      throw new Error("DataLink Packet did not start with DL");
    }
  }
  /**
   * handle errors that arise
   *
   * @private
   * @param   error the error
   */
  handleError(error51) {
    if (this._responseReject) {
      this._responseReject(error51);
    }
    if (this.errorHandler) {
      this.errorHandler(error51);
    } else {
      log("datalink handleError: " + error51.message);
    }
  }
};
var DataLinkResponse = class _DataLinkResponse {
  constructor(type, value, message) {
    this.type = type;
    this.value = value;
    this.message = message;
  }
  isError() {
    return this.type === ERROR;
  }
  toString() {
    return `${this.type} ${this.value} | ${this.message}`;
  }
  static parse(header, data) {
    let value = "";
    const s2 = header.split(" ");
    const type = s2[0];
    let message = "";
    if (type === ID) {
      message = "" + header.substring(3);
    } else if (type === ENDSTREAM || type === INFO || type === OK || type === ERROR) {
      value = s2[1];
      if (data) {
        message = dataViewToString(
          new DataView(data.buffer, 3 + header.length)
        );
      }
    } else {
      log(`unknown DataLink response type: ${type}  ${header}`);
      message = header.substring(type.length + 1);
    }
    return new _DataLinkResponse(type, value, message);
  }
};
var DataLinkPacket = class {
  constructor(header, dataview) {
    this._miniseed = null;
    this._mseed3 = null;
    this._json = null;
    this.header = header;
    this.data = dataview;
    const split = this.header.split(" ");
    this.streamId = split[1];
    this.pktid = split[2];
    this.hppackettime = split[3];
    this.hppacketstart = split[4];
    this.hppacketend = split[5];
    this.dataSize = Number.parseInt(split[6]);
    if (dataview.byteLength < this.dataSize) {
      throw new Error(
        `not enough bytes in dataview for packet:  ${this.dataSize}`
      );
    }
  }
  /**
   * Packet start time as a DateTime.
   *
   * @returns start time
   */
  get packetStart() {
    return hpTimeToDateTime(parseInt(this.hppacketstart));
  }
  /**
   * Packet end time as a DateTime.
   *
   * @returns end time
   */
  get packetEnd() {
    return hpTimeToDateTime(parseInt(this.hppacketend));
  }
  /**
   * Packet time as a DateTime.
   *
   * @returns packet time
   */
  get packetTime() {
    return hpTimeToDateTime(parseInt(this.hppackettime));
  }
  /**
   * is this packet a miniseed packet
   *
   * @returns          true if it is miniseed
   */
  isMiniseed() {
    return isDef(this._miniseed) || this.streamId.endsWith(MSEED_TYPE);
  }
  /**
   * Parsed payload as a miniseed data record, if the streamid
   * ends with '/MSEED', null otherwise.
   *
   * @returns miniseed DataRecord or null
   */
  asMiniseed() {
    if (!isDef(this._miniseed)) {
      if (this.streamId.endsWith(MSEED_TYPE)) {
        this._miniseed = parseSingleDataRecord(this.data);
      } else {
        this._miniseed = null;
      }
    }
    return this._miniseed;
  }
  /**
   * is this packet a miniseed3 packet
   *
   * @returns          true if it is miniseed3
   */
  isMiniseed3() {
    return isDef(this._mseed3) || this.streamId.endsWith(MSEED3_TYPE);
  }
  /**
   * Parsed payload as a miniseed3 data record, if the data format is 3, null otherwise.
   *
   * @returns miniseed3 DataRecord or null
   */
  asMiniseed3() {
    if (!isDef(this._mseed3)) {
      if (this.streamId.endsWith(MSEED3_TYPE)) {
        this._mseed3 = MSeed3Record.parseSingleDataRecord(this.data);
      } else if (this.streamId.endsWith(MSEED_TYPE)) {
        const ms2 = this.asMiniseed();
        if (ms2) {
          this._mseed3 = convertMS2Record(ms2);
        }
      } else {
        this._mseed3 = null;
      }
    }
    return this._mseed3;
  }
  /**
   * is this packet a json packet
   *
   * @returns          true if it is json
   */
  isJson() {
    return isDef(this._json) || this.streamId.endsWith(JSON_TYPE);
  }
  /**
   * Parsed payload as a json if is json, null otherwise.
   *
   * @returns JSON object or null
   */
  asJson() {
    if (!isDef(this._json)) {
      if (this.streamId.endsWith(JSON_TYPE)) {
        this._json = JSON.parse(dataViewToString(this.data));
      } else {
        this._json = null;
      }
    }
    return this._json;
  }
};
var DataLinkIdStats = class _DataLinkIdStats {
  constructor(version3, serverId, capabilities) {
    this.version = version3;
    this.serverId = serverId;
    this.capabilities = capabilities;
  }
  /**
   * Parses the attributes of a <DataLink> xml element.
   *
   * @param  statusEl               DataLink XML element
   * @returns  the id stats
   */
  static parseXMLAttributes(statusEl) {
    const dlIdStats = new _DataLinkIdStats(
      parseUtil._requireAttribute(statusEl, "Version"),
      parseUtil._requireAttribute(statusEl, "ServerID"),
      parseUtil._requireAttribute(statusEl, "Capabilities").split(" ")
    );
    return dlIdStats;
  }
  toString() {
    return `
DataLink:
Version="${this.version}"
Id="${this.serverId}"
Capabilities="${this.capabilities.join(" ")}"`;
  }
};
var DataLinkStats = class _DataLinkStats {
  constructor(startTime, ringVersion, ringSize, packetSize, maximumPacketID, maximumPackets, memoryMappedRing, volatileRing, totalConnections, totalStreams, txPacketRate, txByteRate, rxPacketRate, rxByteRate, earliestPacketID, earliestPacketCreationTime, earliestPacketDataStartTime, earliestPacketDataEndTime, latestPacketID, latestPacketCreationTime, latestPacketDataStartTime, latestPacketDataEndTime) {
    this.startTime = startTime;
    this.ringVersion = ringVersion;
    this.ringSize = ringSize;
    this.packetSize = packetSize;
    this.maximumPacketID = maximumPacketID;
    this.maximumPackets = maximumPackets;
    this.memoryMappedRing = memoryMappedRing;
    this.volatileRing = volatileRing;
    this.totalConnections = totalConnections;
    this.totalStreams = totalStreams;
    this.txPacketRate = txPacketRate;
    this.txByteRate = txByteRate;
    this.rxPacketRate = rxPacketRate;
    this.rxByteRate = rxByteRate;
    this.earliestPacketID = earliestPacketID;
    this.earliestPacketCreationTime = earliestPacketCreationTime;
    this.earliestPacketDataStartTime = earliestPacketDataStartTime;
    this.earliestPacketDataEndTime = earliestPacketDataEndTime;
    this.latestPacketID = latestPacketID;
    this.latestPacketCreationTime = latestPacketCreationTime;
    this.latestPacketDataStartTime = latestPacketDataStartTime;
    this.latestPacketDataEndTime = latestPacketDataEndTime;
  }
  /**
   * Parses the attributes of a <Status> xml element.
   *
   * @param  statusEl   DataLink <Status> XML element
   * @returns  the stats
   */
  static parseXMLAttributes(statusEl) {
    let maxPacketId = 0;
    if (parseUtil._grabAttribute(statusEl, "MaximumPacketID") != null) {
      maxPacketId = parseInt(parseUtil._requireAttribute(statusEl, "MaximumPacketID"));
    }
    const dlStats = new _DataLinkStats(
      daliDateTime(parseUtil._requireAttribute(statusEl, "StartTime")),
      parseUtil._requireAttribute(statusEl, "RingVersion"),
      parseInt(parseUtil._requireAttribute(statusEl, "RingSize")),
      parseInt(parseUtil._requireAttribute(statusEl, "PacketSize")),
      //parseInt(parseUtil._grabAttribute(statusEl, "MaximumPacketID")),
      maxPacketId,
      parseInt(parseUtil._requireAttribute(statusEl, "MaximumPackets")),
      parseUtil._requireAttribute(statusEl, "MemoryMappedRing") === "TRUE",
      parseUtil._requireAttribute(statusEl, "VolatileRing") === "TRUE",
      parseInt(parseUtil._requireAttribute(statusEl, "TotalConnections")),
      parseInt(parseUtil._requireAttribute(statusEl, "TotalStreams")),
      parseFloat(parseUtil._requireAttribute(statusEl, "TXPacketRate")),
      parseFloat(parseUtil._requireAttribute(statusEl, "TXByteRate")),
      parseFloat(parseUtil._requireAttribute(statusEl, "RXPacketRate")),
      parseFloat(parseUtil._requireAttribute(statusEl, "RXByteRate")),
      parseInt(parseUtil._requireAttribute(statusEl, "EarliestPacketID")),
      daliDateTime(
        parseUtil._requireAttribute(statusEl, "EarliestPacketCreationTime")
      ),
      daliDateTime(
        parseUtil._requireAttribute(statusEl, "EarliestPacketDataStartTime")
      ),
      daliDateTime(
        parseUtil._requireAttribute(statusEl, "EarliestPacketDataEndTime")
      ),
      parseInt(parseUtil._requireAttribute(statusEl, "LatestPacketID")),
      daliDateTime(
        parseUtil._requireAttribute(statusEl, "LatestPacketCreationTime")
      ),
      daliDateTime(
        parseUtil._requireAttribute(statusEl, "LatestPacketDataStartTime")
      ),
      daliDateTime(
        parseUtil._requireAttribute(statusEl, "LatestPacketDataEndTime")
      )
    );
    return dlStats;
  }
  toString() {
    return `
Status:
StartTime="${this.startTime.toISO()}"
RingVersion="${this.ringVersion}"
RingSize="${this.ringSize}"
PacketSize="${this.packetSize}"
MaximumPacketID="${this.maximumPacketID}"
MaximumPackets="${this.maximumPackets}"
MemoryMappedRing="${this.memoryMappedRing}"
VolatileRing="${this.volatileRing}"
TotalConnections="${this.totalConnections}"
TotalStreams="${this.totalStreams}"
TXPacketRate="${this.txPacketRate}"
TXByteRate="${this.txByteRate}"
RXPacketRate="${this.rxPacketRate}"
RXByteRate="${this.rxByteRate}"
EarliestPacketID="${this.earliestPacketID}"
EarliestPacketCreationTime="${this.earliestPacketCreationTime.toISO()}"
EarliestPacketDataStartTime="${this.earliestPacketDataStartTime.toISO()}"
EarliestPacketDataEndTime="${this.earliestPacketDataEndTime.toISO()}"
LatestPacketID="${this.latestPacketID}"
LatestPacketCreationTime="${this.latestPacketCreationTime.toISO()}"
LatestPacketDataStartTime="${this.latestPacketDataStartTime.toISO()}"
LatestPacketDataEndTime="${this.latestPacketDataEndTime.toISO()}"
    `;
  }
};
var ThreadStat = class _ThreadStat {
  constructor(flags, type, port) {
    this.flags = flags;
    this.type = type;
    this.port = port;
  }
  /**
   * Parses the attributes of a <Status> xml element.
   *
   * @param  statusEl   DataLink <Status> XML element
   * @returns  the stats
   */
  static parseXMLAttributes(statusEl) {
    const threadStats = new _ThreadStat(
      parseUtil._requireAttribute(statusEl, "Flags").split(" "),
      parseUtil._requireAttribute(statusEl, "Type").split(" "),
      parseInt(parseUtil._requireAttribute(statusEl, "Port"))
    );
    return threadStats;
  }
  toString() {
    return `Thread  Port: ${this.port} Flags: ${this.flags.join(" ")} Type: ${this.type.join(" ")}`;
  }
};
var StatusResponse = class _StatusResponse {
  constructor(idStats, datalinkStats, threadStats) {
    this.rawXml = "";
    this.idStats = idStats;
    this.datalinkStats = datalinkStats;
    this.threadStats = threadStats;
  }
  static fromDatalinkResponse(daliResp) {
    if (daliResp.type === INFO) {
      const daliXml = new DOMParser().parseFromString(
        daliResp.message,
        "text/xml"
      );
      const sResp = _StatusResponse.fromXML(daliXml.documentElement);
      sResp.rawXml = daliResp.message;
      return sResp;
    } else {
      throw new Error("Datalink Response not OK", { cause: daliResp });
    }
  }
  static fromXML(daliXML) {
    const idStats = DataLinkIdStats.parseXMLAttributes(daliXML);
    const dlStats = DataLinkStats.parseXMLAttributes(
      daliXML.getElementsByTagName("Status")[0]
    );
    const threadListEl = daliXML.getElementsByTagName("ServerThreads")[0];
    let threads = [];
    if (threadListEl) {
      threads = Array.from(threadListEl.getElementsByTagName("Thread")).map(
        (threadEl) => ThreadStat.parseXMLAttributes(threadEl)
      );
    }
    return new _StatusResponse(idStats, dlStats, threads);
  }
  toString() {
    return `
${this.idStats.toString()}
${this.datalinkStats.toString()}
${this.threadStats.join("\n")}`;
  }
};
var StreamStat = class _StreamStat {
  constructor(name, earliestPacketID, earliestPacketDataStartTime, earliestPacketDataEndTime, latestPacketID, latestPacketDataStartTime, latestPacketDataEndTime, dataLatency) {
    this.name = name;
    this.earliestPacketID = earliestPacketID;
    this.earliestPacketDataStartTime = earliestPacketDataStartTime;
    this.earliestPacketDataEndTime = earliestPacketDataEndTime;
    this.latestPacketID = latestPacketID;
    this.latestPacketDataStartTime = latestPacketDataStartTime;
    this.latestPacketDataEndTime = latestPacketDataEndTime;
    this.dataLatency = dataLatency;
  }
  static parseXMLAttributes(statusEl) {
    let earlyDataEnd = parseUtil._grabAttribute(statusEl, "EarliestPacketDataEndTime");
    if (earlyDataEnd == null) {
      earlyDataEnd = parseUtil._requireAttribute(statusEl, "EarliestPacketDataStartTime");
    }
    const sStat = new _StreamStat(
      parseUtil._requireAttribute(statusEl, "Name"),
      parseInt(parseUtil._requireAttribute(statusEl, "EarliestPacketID")),
      daliDateTime(
        parseUtil._requireAttribute(statusEl, "EarliestPacketDataStartTime")
      ),
      daliDateTime(
        earlyDataEnd
        //  parseUtil._requireAttribute(statusEl, "EarliestPacketDataEndTime"),
      ),
      parseInt(parseUtil._requireAttribute(statusEl, "LatestPacketID")),
      daliDateTime(
        parseUtil._requireAttribute(statusEl, "LatestPacketDataStartTime")
      ),
      daliDateTime(
        parseUtil._requireAttribute(statusEl, "LatestPacketDataEndTime")
      ),
      parseFloat(parseUtil._requireAttribute(statusEl, "DataLatency"))
    );
    return sStat;
  }
  toString() {
    return `
    Name: ${this.name}
    EarliestPacketID="${this.earliestPacketID}"
    EarliestPacketDataStartTime="${this.earliestPacketDataStartTime.toISO()}"
    EarliestPacketDataEndTime="${this.earliestPacketDataEndTime.toISO()}"
    LatestPacketID="${this.latestPacketID}"
    LatestPacketDataStartTime="${this.latestPacketDataStartTime.toISO()}"
    LatestPacketDataEndTime="${this.latestPacketDataEndTime.toISO()}"
    DataLatency=${this.dataLatency}
    `;
  }
};
var StreamsResponse = class _StreamsResponse {
  constructor(datalinkStats, streams) {
    this.datalinkStats = datalinkStats;
    this.streams = streams;
  }
  static fromDatalinkResponse(daliResp) {
    if (daliResp.type === INFO) {
      const daliXml = new DOMParser().parseFromString(
        daliResp.message,
        "text/xml"
      );
      return _StreamsResponse.fromXML(daliXml.documentElement);
    } else {
      throw new Error("Datalink Response not OK", { cause: daliResp });
    }
  }
  /*
  <DataLink Version="2018.078"
  ServerID="South Carolina Seismic Network"
  Capabilities="DLPROTO:1.0 PACKETSIZE:512 WRITE">
  <Status
    StartTime="2022-09-21 12:13:29"
    RingVersion="1"
    RingSize="1073741824"
    PacketSize="512"
    MaximumPacketID="16777215"
    MaximumPackets="1698952"
    MemoryMappedRing="TRUE"
    VolatileRing="FALSE"
    TotalConnections="9"
    TotalStreams="90"
    TXPacketRate="57.0"
    TXByteRate="29167.9"
    RXPacketRate="18.0"
    RXByteRate="9210.9"
    EarliestPacketID="11763348"
    EarliestPacketCreationTime="2022-10-03 12:56:43.520738"
    EarliestPacketDataStartTime="2022-10-03 12:56:40.860000"
    EarliestPacketDataEndTime="2022-10-03 12:56:42.875000"
    LatestPacketID="13462299"
    LatestPacketCreationTime="2022-10-04 15:11:24.786990"
    LatestPacketDataStartTime="2022-10-04 15:11:19.580000"
    LatestPacketDataEndTime="2022-10-04 15:11:22.785000" />
    <StreamList TotalStreams="90" SelectedStreams="3">
      <Stream Name="CO_JSC_00_HHE/MSEED" EarliestPacketID="11763363" EarliestPacketDataStartTime="2022-10-03 12:56:37.178392" EarliestPacketDataEndTime="2022-10-03 12:56:40.808392" LatestPacketID="13462285" LatestPacketDataStartTime="2022-10-04 15:11:15.808392" LatestPacketDataEndTime="2022-10-04 15:11:18.788392" DataLatency="6.0" />
      <Stream Name="CO_JSC_00_HHN/MSEED" EarliestPacketID="11763389" EarliestPacketDataStartTime="2022-10-03 12:56:38.108392" EarliestPacketDataEndTime="2022-10-03 12:56:41.398392" LatestPacketID="13462284" LatestPacketDataStartTime="2022-10-04 15:11:15.668392" LatestPacketDataEndTime="2022-10-04 15:11:18.408392" DataLatency="6.4" />
      <Stream Name="CO_JSC_00_HHZ/MSEED" EarliestPacketID="11763402" EarliestPacketDataStartTime="2022-10-03 12:56:38.908392" EarliestPacketDataEndTime="2022-10-03 12:56:42.688392" LatestPacketID="13462252" LatestPacketDataStartTime="2022-10-04 15:11:14.428392" LatestPacketDataEndTime="2022-10-04 15:11:17.858392" DataLatency="6.9" />
    </StreamList>
  </DataLink>
     */
  static fromXML(daliXML) {
    const statusEl = daliXML.getElementsByTagName("Status")[0];
    const dlStats = DataLinkStats.parseXMLAttributes(statusEl);
    const streamListEl = daliXML.getElementsByTagName("StreamList")[0];
    const streamElList = streamListEl.getElementsByTagName("Stream");
    const streams = Array.from(streamElList).map(
      (streamEl) => StreamStat.parseXMLAttributes(streamEl)
    );
    const streamResp = new _StreamsResponse(dlStats, streams);
    return streamResp;
  }
  toString() {
    return `${this.datalinkStats.toString()}
    ${this.streams.map((s2) => s2.toString()).join("\n")}
    `;
  }
};
var ConnectionsResponse = class _ConnectionsResponse {
  constructor(daliXML) {
    this.daliXML = daliXML;
  }
  static fromDatalinkResponse(daliResp) {
    if (daliResp.type === INFO) {
      return new _ConnectionsResponse(daliResp.message);
    } else {
      throw new Error("Datalink Response not OK", { cause: daliResp });
    }
  }
  static fromXML(daliXML) {
    const xmlString = new XMLSerializer().serializeToString(daliXML);
    return new _ConnectionsResponse(xmlString);
  }
  toString() {
    return `${this.daliXML.toString()}`;
  }
};
function daliDateTime(dalitime) {
  const iso = dalitime.replace(" ", "T");
  return isoToDateTime(iso);
}
function dateTimeToHPTime(m) {
  return m.valueOf() * 1e3;
}
function hpTimeToDateTime(hptime) {
  return DateTime.fromMillis(hptime / 1e3, UTC_OPTIONS);
}
function stringToUint8Array(dataString) {
  let binaryData;
  if (isNonEmptyStringArg(dataString)) {
    binaryData = new Uint8Array(dataString.length);
    for (let i = 0; i < dataString.length; i++) {
      binaryData[i] = dataString.charCodeAt(i);
    }
  } else {
    binaryData = new Uint8Array(0);
  }
  return binaryData;
}

// src/seedlink4.mts
var seedlink4_exports = {};
__export(seedlink4_exports, {
  AUTH_COMMAND: () => AUTH_COMMAND,
  BYE_COMMAND: () => BYE_COMMAND,
  DATA_COMMAND: () => DATA_COMMAND,
  ENDFETCH_COMMAND: () => ENDFETCH_COMMAND,
  END_COMMAND: () => END_COMMAND,
  HELLO_COMMAND: () => HELLO_COMMAND,
  INFO_COMMAND: () => INFO_COMMAND,
  MINISEED_2_FORMAT: () => MINISEED_2_FORMAT,
  MINISEED_3_FORMAT: () => MINISEED_3_FORMAT,
  SEEDLINK4_PROTOCOL: () => SEEDLINK4_PROTOCOL,
  SEEDLINK4_SLPROTO: () => SEEDLINK4_SLPROTO,
  SELECT_COMMAND: () => SELECT_COMMAND,
  SEPacket: () => SEPacket,
  SE_PACKET_SIGNATURE: () => SE_PACKET_SIGNATURE,
  SLPROTO_COMMAND: () => SLPROTO_COMMAND,
  SL_OK: () => SL_OK,
  STATION_COMMAND: () => STATION_COMMAND,
  SeedlinkConnection: () => SeedlinkConnection,
  USERAGENT_COMMAND: () => USERAGENT_COMMAND,
  WS_SEEDLINK4_SUBPROTOCOL: () => WS_SEEDLINK4_SUBPROTOCOL,
  createDataTimeCommand: () => createDataTimeCommand
});
var SEEDLINK4_SLPROTO = "SLPROTO";
var SEEDLINK4_PROTOCOL = `${SEEDLINK4_SLPROTO}:4.0`;
var WS_SEEDLINK4_SUBPROTOCOL = `SeedLink4.0`;
var MINISEED_2_FORMAT = "2";
var MINISEED_3_FORMAT = "3";
var SE_PACKET_SIGNATURE = "SE";
var END_COMMAND = "END";
var ENDFETCH_COMMAND = "ENDFETCH";
var AUTH_COMMAND = "AUTH";
var BYE_COMMAND = "BYE";
var DATA_COMMAND = "DATA";
var HELLO_COMMAND = "HELLO";
var INFO_COMMAND = "INFO";
var SELECT_COMMAND = "SELECT";
var SLPROTO_COMMAND = "SLPROTO";
var STATION_COMMAND = "STATION";
var USERAGENT_COMMAND = "USERAGENT";
var SL_OK = "OK";
var useLittleEndian = true;
var SEPacket = class _SEPacket {
  constructor(dataFormat, dataSubformat, payloadLength, sequence, stationId) {
    this.dataFormat = dataFormat;
    this.dataSubformat = dataSubformat;
    this.payloadLength = payloadLength;
    this.sequence = sequence;
    this.stationId = stationId;
    this._miniseed = null;
    this._mseed3 = null;
    this._json = null;
    this._rawPayload = null;
  }
  static parse(data) {
    let sePacket;
    if (data.byteLength < 17) {
      throw new Error(
        "message too small to be SE packet: " + data.byteLength + " " + dataViewToString(new DataView(data))
      );
    }
    const slHeader = new DataView(data, 0, 17);
    const sig = String.fromCharCode(slHeader.getUint8(0), slHeader.getUint8(1));
    if (sig === SE_PACKET_SIGNATURE) {
      const dataFormat = slHeader.getUint8(2);
      const dataSubformat = slHeader.getUint8(3);
      const payloadLength = slHeader.getUint32(4, useLittleEndian);
      const sequenceNum = slHeader.getBigUint64(8, useLittleEndian);
      const stationIdLength = slHeader.getUint8(16);
      const stationIdDV = new DataView(data, 17, stationIdLength);
      const stationId = dataViewToString(stationIdDV);
      const dataView = new DataView(
        data,
        17 + stationIdLength,
        data.byteLength - (17 + stationIdLength)
      );
      sePacket = new _SEPacket(
        String.fromCharCode(dataFormat),
        String.fromCharCode(dataSubformat),
        payloadLength,
        sequenceNum,
        stationId
      );
      sePacket._rawPayload = dataView;
      if (dataFormat === 50) {
        sePacket._miniseed = parseSingleDataRecord(dataView);
      } else if (dataFormat === 51) {
        sePacket._mseed3 = MSeed3Record.parseSingleDataRecord(dataView);
      } else if (dataFormat === 74) {
        const jsonData = JSON.parse(dataViewToString(dataView));
        sePacket._json = jsonData;
      }
    } else {
      throw new Error(
        "Not a seedlink4 packet, no starting SE: " + slHeader.getInt8(0) + " " + slHeader.getInt8(1)
      );
    }
    return sePacket;
  }
  /**
   * is this packet a miniseed packet
   *
   * @returns          true if it is miniseed
   */
  isMiniseed() {
    return isDef(this._miniseed) || this.dataFormat === MINISEED_2_FORMAT;
  }
  /**
   * Parsed payload as a miniseed data record, if the streamid
   * ends with '/MSEED', null otherwise.
   *
   * @returns miniseed DataRecord or null
   */
  asMiniseed() {
    if (!isDef(this._rawPayload)) {
      throw new Error(
        `payload is missing in packet from ${this.stationId}, seq: ${this.sequence}`
      );
    }
    if (!isDef(this._miniseed)) {
      if (this.dataFormat === MINISEED_2_FORMAT && isDef(this._rawPayload)) {
        this._miniseed = parseSingleDataRecord(this._rawPayload);
      } else {
        this._miniseed = null;
      }
    }
    return this._miniseed;
  }
  /**
   * is this packet a miniseed3 packet
   *
   * @returns          true if it is miniseed3
   */
  isMiniseed3() {
    return isDef(this._mseed3) || this.dataFormat === MINISEED_3_FORMAT;
  }
  /**
   * Parsed payload as a miniseed3 data record, if the data format is 3, null otherwise.
   *
   * @returns miniseed3 DataRecord or null
   */
  asMiniseed3() {
    if (!isDef(this._rawPayload)) {
      throw new Error(
        `payload is missing in packet from ${this.stationId}, seq: ${this.sequence}`
      );
    }
    if (!isDef(this._mseed3)) {
      if (this.dataFormat === MINISEED_3_FORMAT && isDef(this._rawPayload)) {
        this._mseed3 = MSeed3Record.parseSingleDataRecord(
          this._rawPayload
        );
      } else if (this.isMiniseed()) {
        const ms2 = this.asMiniseed();
        if (ms2) {
          this._mseed3 = convertMS2Record(ms2);
        }
      } else {
        this._mseed3 = null;
      }
    }
    return this._mseed3;
  }
};
function createDataTimeCommand(startTime, endTime) {
  const endTimeStr = isDef(endTime) ? endTime.toISO() : "";
  return `DATA ALL ${startTime.toISO()} ${endTimeStr}`;
}
var SeedlinkConnection = class {
  constructor(url2, requestConfig, receivePacketFn, errorHandler) {
    this.webSocket = null;
    this.url = url2;
    this.requestConfig = requestConfig;
    this.receivePacketFn = receivePacketFn;
    this.errorHandler = errorHandler;
    this.logCommandFn = (msg) => {
    };
    this.closeFn = null;
    this.endCommand = END_COMMAND;
    this.agent = "seisplotjs";
    this.agentVersion = version;
    this.subprotocol = WS_SEEDLINK4_SUBPROTOCOL;
  }
  setAgent(agent) {
    this.agent = agent.trim().replaceAll(/\w+/g, "_");
  }
  setOnError(errorHandler) {
    this.errorHandler = errorHandler;
  }
  setOnClose(closeFn) {
    this.closeFn = closeFn;
  }
  connect() {
    return this.interactiveConnect().then(() => {
      return this.sendHello();
    }).then((lines) => {
      if (this.checkProto(lines)) {
        return true;
      } else {
        throw new Error(`${SEEDLINK4_PROTOCOL} not found in HELLO response: ${lines.join("\n")}`);
      }
    }).then(() => {
      return this.sendSLProto("4.0");
    }).then(() => {
      return this.sendCmdArray([
        `${USERAGENT_COMMAND} ${this.agent}/${this.agentVersion} (seisplotjs/${version})`
      ]);
    }).then(() => {
      return this.sendCmdArray(this.requestConfig);
    }).then((val) => {
      if (this.webSocket === null) {
        throw new Error("websocket is null");
      }
      this.webSocket.onmessage = (event) => {
        this.handle(event);
      };
      const cmd = `${this.endCommand}\r
`;
      if (this.logCommandFn) {
        this.logCommandFn(cmd);
      }
      this.webSocket.send(cmd);
      return val;
    }).catch((err) => {
      this.close();
      const insureErr = err instanceof Error ? err : new Error(stringify(err));
      if (this.errorHandler) {
        this.errorHandler(insureErr);
      } else {
        throw insureErr;
      }
    });
  }
  interactiveConnect() {
    if (this.webSocket) {
      this.webSocket.close();
      this.webSocket = null;
    }
    return new Promise((resolve, reject) => {
      try {
        const webSocket = new WebSocket(this.url, this.subprotocol);
        this.webSocket = webSocket;
        webSocket.binaryType = "arraybuffer";
        webSocket.onopen = () => {
          resolve(this);
        };
        webSocket.onerror = (event) => {
          const evtError = toError(event);
          this.handleError(evtError);
          reject(evtError);
        };
        webSocket.onclose = (closeEvent) => {
          if (this.closeFn) {
            this.closeFn(closeEvent);
          }
          if (this.webSocket) {
            this.webSocket = null;
          }
        };
      } catch (err) {
        const evtError = toError(err);
        this.close();
        reject(evtError);
      }
    }).then(function(sl4) {
      return sl4;
    }).catch((e) => {
      if (!this.webSocket?.protocol || this.webSocket.protocol.length === 0) {
        throw new Error(`fail to create websocket, possible due to subprotocol: sent subprotocol=${this.subprotocol} received empty`);
      }
      throw e;
    });
  }
  checkProto(lines) {
    const sl = lines[0].split("::");
    const caps = sl[1].trim().split(" ");
    for (const c of caps) {
      if (c === SEEDLINK4_PROTOCOL) {
        return true;
      }
    }
    return false;
  }
  close() {
    if (this.webSocket) {
      this.webSocket.close();
    }
    this.webSocket = null;
  }
  handle(event) {
    if (event.data instanceof ArrayBuffer || event.data instanceof SharedArrayBuffer) {
      const rawdata = event.data;
      const data = new Uint8Array(rawdata);
      if (data[0] === 83 && data[1] === 69) {
        this.handleSEPacket(event);
      } else {
        this.close();
        this.handleError(
          new Error(
            `Packet does not look like SE packet: ${data[0]} ${data[1]}`
          )
        );
      }
    } else {
      this.close();
      this.handleError(new Error("event.data is not ArrayBufferLike"));
    }
  }
  handleSEPacket(event) {
    if (event.data instanceof ArrayBuffer || event.data instanceof SharedArrayBuffer) {
      const data = event.data;
      try {
        const out = SEPacket.parse(data);
        this.receivePacketFn(out);
      } catch (e) {
        this.close();
        this.handleError(toError(e));
      }
    } else {
      this.close();
      this.handleError(new Error("event.data is not ArrayBufferLike"));
    }
  }
  isConnected() {
    return this.webSocket !== null;
  }
  /**
   * Sends initial HELLO to server and waits for response.
   *
   * @returns            Promise that resolves to the response from the server.
   */
  sendHello() {
    const webSocket = this.webSocket;
    const promise2 = new Promise((resolve, reject) => {
      if (webSocket) {
        webSocket.onmessage = (event) => {
          if (event.data instanceof ArrayBuffer || event.data instanceof SharedArrayBuffer) {
            const data = event.data;
            const replyMsg = dataViewToString(new DataView(data));
            if (this.logCommandFn) {
              this.logCommandFn(replyMsg);
            }
            const lines = replyMsg.trim().split("\r");
            if (lines.length === 2) {
              resolve(lines);
            } else {
              reject(new Error("not 2 lines: " + replyMsg));
            }
          } else {
            this.close();
            this.errorHandler(new Error("event.data is not ArrayBufferLike"));
          }
        };
        const cmd = `${HELLO_COMMAND}\r`;
        if (this.logCommandFn) {
          this.logCommandFn(cmd);
        }
        webSocket.send(cmd);
      } else {
        reject(new Error("webSocket has been closed"));
      }
    });
    return promise2;
  }
  sendSLProto(version3) {
    return this.createCmdPromise(`${SEEDLINK4_SLPROTO} ${version3}`);
  }
  /**
   * Sends an array of commands, each as a Promise waiting for the 'OK' response
   * before sending the next.
   *
   * @param   cmd array of commands to send
   * @returns      Promise that resolves to the 'OK' returned by the last
   *   command if successful, or rejects on the first failure.
   */
  sendCmdArray(cmd) {
    return cmd.reduce((accum, next) => {
      return accum.then(() => {
        return this.createCmdPromise(next);
      });
    }, Promise.resolve(SL_OK));
  }
  /**
   * creates a Promise that sends a command and waits resolved with the result.
   *
   * @param   mycmd command string to send.
   * @returns        Promise that resolves to the reply from the server.
   */
  createCmdPromise(mycmd) {
    const mythis = this;
    const webSocket = this.webSocket;
    const promise2 = new Promise(function(resolve, reject) {
      if (webSocket) {
        webSocket.onmessage = (event) => {
          if (event.data instanceof ArrayBuffer || event.data instanceof SharedArrayBuffer) {
            const data = event.data;
            const replyMsg = dataViewToString(new DataView(data)).trim();
            if (mythis.logCommandFn) {
              mythis.logCommandFn(replyMsg);
            }
            if (replyMsg === SL_OK) {
              resolve(replyMsg);
            } else {
              reject(new Error("msg not OK: " + replyMsg));
            }
          } else {
            mythis.close();
            mythis.errorHandler(new Error("event.data is not ArrayBufferLike"));
          }
        };
        if (mythis.logCommandFn) {
          mythis.logCommandFn(mycmd);
        }
        webSocket.send(mycmd + "\r\n");
      } else {
        reject(new Error("webSocket has been closed"));
      }
    });
    return promise2;
  }
  /**
   * handle errors that arise
   *
   * @private
   * @param   error the error
   */
  handleError(error51) {
    if (this.errorHandler) {
      this.errorHandler(error51);
    } else {
      log("seedlink4 handleError: " + error51.message);
    }
  }
};

// src/filter.mts
var filter_exports = {};
__export(filter_exports, {
  BAND_PASS: () => BAND_PASS,
  HIGH_PASS: () => HIGH_PASS,
  LOW_PASS: () => LOW_PASS,
  add: () => add,
  amplitude: () => amplitude,
  applyFilter: () => applyFilter,
  createButterworth: () => createButterworth,
  createChebyshevI: () => createChebyshevI,
  createChebyshevII: () => createChebyshevII,
  differentiate: () => differentiate,
  envelope: () => envelope,
  gainCorrect: () => gainCorrect,
  getPassband: () => getPassband,
  hilbert: () => hilbert,
  integrate: () => integrate,
  lineFit: () => lineFit,
  mul: () => mul,
  rMean: () => rMean,
  removeTrend: () => removeTrend
});
var BAND_PASS = "BANDPASS";
var LOW_PASS = "LOWPASS";
var HIGH_PASS = "HIGHPASS";
function amplitude(real, imag) {
  return Math.hypot(real, imag);
}
function rMean(seis) {
  if (seis instanceof Seismogram) {
    const meanVal = seis.mean();
    const rmeanSeismogram = new Seismogram(
      seis.segments.map((s2) => {
        const demeanY = s2.y.map(function(d) {
          return d - meanVal;
        });
        const out = s2.cloneWithNewData(demeanY);
        return out;
      })
    );
    return rmeanSeismogram;
  } else {
    throw new Error("rMean arg not a Seismogram");
  }
}
function lineFit(seis, referenceTime) {
  if (seis.numPoints === 0) {
    throw new Error(`cannot lineFit a seismogram with no points`);
  }
  const rn = seis.numPoints;
  let sumx = 0;
  let sumy = 0;
  let sumxy = 0;
  let sumx2 = 0;
  let sumy2 = 0;
  referenceTime = referenceTime ? referenceTime : seis.start;
  const x1 = referenceTime.toMillis() / 1e3;
  seis.segments.forEach((seg) => {
    const seg_start_x = seg.start.toMillis() / 1e3 - x1;
    const dx = 1 / seg.sampleRate;
    const Y = seg.y;
    for (let i = 0; i < Y.length; i++) {
      const yi = Y[i];
      const xi = seg_start_x + dx * i;
      sumx = sumx + xi;
      sumy = sumy + yi;
      sumxy = sumxy + xi * yi;
      sumx2 = sumx2 + xi * xi;
      sumy2 = sumy2 + yi * yi;
    }
  });
  const d = rn * sumx2 - sumx * sumx;
  const b = d !== 0 ? (sumx2 * sumy - sumx * sumxy) / d : 0;
  const a = d !== 0 ? (rn * sumxy - sumx * sumy) / d : 0;
  const sig2 = (sumy2 + rn * b * b + a * a * sumx2 - 2 * b * sumy - 2 * a * sumxy + 2 * b * a * sumx) / (seis.numPoints - 1);
  const sig = Math.sqrt(sig2);
  const siga2 = rn * sig2 / d;
  const sigb2 = sig2 * sumx2 / d;
  const siga = Math.sqrt(siga2);
  const sigb = Math.sqrt(sigb2);
  let cc = (rn * sumxy - sumx * sumy) / Math.sqrt(d * (rn * sumy2 - sumy * sumy));
  cc = Math.abs(cc);
  return {
    slope: a,
    intercept: b,
    reference_time: referenceTime,
    sigma: sig,
    sigma_a: siga,
    sigma_b: sigb,
    correlation: cc
  };
}
function removeTrend(seis, fitLine) {
  if (seis instanceof Seismogram) {
    const linfit = fitLine ? fitLine : lineFit(seis);
    if (Number.isNaN(linfit.slope) || Number.isNaN(linfit.intercept)) {
      throw new Error(
        `Can't remove trend with NaN, slope: ${linfit.slope} int: ${linfit.intercept}`
      );
    }
    const ref_secs = linfit.reference_time.toMillis() / 1e3;
    const rtr_segments = seis.segments.map((seg) => {
      const start_secs = seg.start.toMillis() / 1e3;
      const start_offset = start_secs - ref_secs;
      const dx = 1 / seg.sampleRate;
      const rtr_y = seg.y.map((y2, idx) => {
        const out = y2 - (start_offset + dx * idx) * linfit.slope - linfit.intercept;
        return out;
      });
      const rtr_seg = seg.cloneWithNewData(rtr_y);
      return rtr_seg;
    });
    return new Seismogram(rtr_segments);
  } else {
    throw new Error("removeTrend arg not a Seismogram");
  }
}
function gainCorrect(seis, instrumentSensitivity) {
  const gain = instrumentSensitivity.sensitivity;
  const out = mul(seis, 1 / gain);
  out.segments.forEach((s2) => s2.yUnit = instrumentSensitivity.inputUnits);
  return out;
}
function mul(seis, factor) {
  if (seis instanceof Seismogram) {
    const gainSeismogram = new Seismogram(
      seis.segments.map((s2) => {
        let gainY;
        if (s2.y instanceof Int32Array || s2.y instanceof Float32Array) {
          gainY = Float32Array.from(s2.y);
        } else {
          gainY = Float64Array.from(s2.y);
        }
        gainY = gainY.map(function(d) {
          return d * factor;
        });
        const outS = s2.cloneWithNewData(gainY);
        return outS;
      })
    );
    return gainSeismogram;
  } else {
    throw new Error(`Expected Seismogram but was ${typeof seis}`);
  }
}
function add(seis, factor) {
  if (seis instanceof Seismogram) {
    const gainSeismogram = new Seismogram(
      seis.segments.map((s2) => {
        let gainY;
        if (s2.y instanceof Int32Array || s2.y instanceof Float32Array) {
          gainY = Float32Array.from(s2.y);
        } else {
          gainY = Float64Array.from(s2.y);
        }
        gainY = gainY.map(function(d) {
          return d + factor;
        });
        const outS = s2.cloneWithNewData(gainY);
        return outS;
      })
    );
    return gainSeismogram;
  } else {
    throw new Error(`Expected Seismogram but was ${typeof seis}`);
  }
}
function getPassband(type) {
  if (type === LOW_PASS) {
    return LOWPASS;
  } else if (type === BAND_PASS) {
    return PassbandType.BANDPASS;
  } else if (type === HIGH_PASS) {
    return PassbandType.HIGHPASS;
  } else {
    throw new Error(`unknown pass band: ${type}`);
  }
}
function createButterworth(numPoles, passband, lowFreqCorner, highFreqCorner, delta) {
  const passbandtype = getPassband(passband);
  return new Butterworth(
    numPoles,
    passbandtype,
    lowFreqCorner,
    highFreqCorner,
    delta
  );
}
function createChebyshevI(numPoles, epsilon3, passband, lowFreqCorner, highFreqCorner, delta) {
  const passbandtype = getPassband(passband);
  return new ChebyshevI(
    numPoles,
    epsilon3,
    passbandtype,
    lowFreqCorner,
    highFreqCorner,
    delta
  );
}
function createChebyshevII(numPoles, epsilon3, passband, lowFreqCorner, highFreqCorner, delta) {
  const passbandtype = getPassband(passband);
  return new ChebyshevII(
    numPoles,
    epsilon3,
    passbandtype,
    lowFreqCorner,
    highFreqCorner,
    delta
  );
}
function applyFilter(iirFilter, seis) {
  if (Math.abs(iirFilter.getDelta() - seis.samplePeriod) / seis.samplePeriod > 1e-3) {
    throw new Error(
      `Filter, delta=${iirFilter.getDelta()}, has different delta from seis, ${1 / seis.sampleRate}`
    );
  }
  const filteredSegments = [];
  for (let i = 0; i < seis.segments.length; i++) {
    const outData = Float32Array.from(seis.segments[i].y);
    iirFilter.filterInPlace(outData);
    filteredSegments.push(seis.segments[i].cloneWithNewData(outData));
  }
  return new Seismogram(filteredSegments);
}
function envelope(seis) {
  if (seis.isContiguous()) {
    const seisY = seis.y;
    const s2 = hilbert(seis);
    const hilbertY = s2.y;
    let outY;
    if (seis.y instanceof Int32Array || seis.y instanceof Float32Array) {
      outY = new Float32Array(seisY.length);
    } else {
      outY = new Float64Array(seisY.length);
    }
    for (let n2 = 0; n2 < seisY.length; n2++) {
      outY[n2] = Math.sqrt(hilbertY[n2] * hilbertY[n2] + seisY[n2] * seisY[n2]);
    }
    return seis.cloneWithNewData(outY);
  } else {
    throw new Error("Cannot take envelope of non-contiguous seismogram");
  }
}
function hilbert(seis, n2, lowEdge, highEdge) {
  if (seis.isContiguous()) {
    let seisY;
    if (seis.y instanceof Float32Array) {
      seisY = seis.y;
    } else {
      seisY = Float32Array.from(seis.y);
    }
    if (!isDef(n2)) {
      n2 = 10;
    }
    if (!isDef(lowEdge)) {
      lowEdge = 0.05;
    }
    if (!isDef(highEdge)) {
      highEdge = 0.95;
    }
    const hilbert2 = new CenteredHilbertTransform(n2, lowEdge, highEdge);
    const coeff = hilbert2.getCoefficients();
    for (const c of coeff) {
      if (Number.isNaN(c)) {
        throw new Error(`Hilbert FIR coeff includes NaN: ${coeff.join()}`);
      }
    }
    const hilbertY = hilbert2.filter(seisY);
    const s2 = seis.cloneWithNewData(hilbertY);
    return s2;
  } else {
    throw new Error("Cannot take hilbert of non-contiguous seismogram");
  }
}
function differentiate(seis) {
  if (seis instanceof Seismogram) {
    const diffSeismogram = new Seismogram(
      seis.segments.map((s2) => {
        const origY = s2.y;
        const sampRate = 1 * s2.sampleRate;
        const diffY = new Float32Array(origY.length - 1);
        for (let i = 0; i < diffY.length; i++) {
          diffY[i] = (origY[i + 1] - origY[i]) * sampRate;
        }
        const out = s2.cloneWithNewData(diffY);
        out.startTime = out.startTime.plus(
          Duration.fromMillis(1e3 / out.sampleRate / 2)
        );
        out.yUnit = out.yUnit + "/s";
        return out;
      })
    );
    return diffSeismogram;
  } else {
    throw new Error("diff arg not a Seismogram");
  }
}
function integrate(seis, integrationConst = 0) {
  let prior = integrationConst;
  if (seis instanceof Seismogram) {
    const intSeismogram = new Seismogram(
      seis.segments.map((s2) => {
        const origY = s2.y;
        const sampPeriod = s2.samplePeriod;
        const intY = new Float32Array(origY.length + 1);
        intY[0] = prior;
        for (let i = 1; i < intY.length; i++) {
          prior += sampPeriod * origY[i - 1];
          intY[i] = prior;
        }
        const out = s2.cloneWithNewData(intY);
        out.startTime = out.startTime.minus(
          Duration.fromMillis(1e3 / out.sampleRate / 2)
        );
        if (out.yUnit.endsWith("/s")) {
          out.yUnit = out.yUnit.slice(0, out.yUnit.length - 2);
        } else {
          out.yUnit += "s";
        }
        return out;
      })
    );
    return intSeismogram;
  } else {
    throw new Error("integrate arg not a Seismogram");
  }
}

// src/organizeddisplay.mts
var organizeddisplay_exports = {};
__export(organizeddisplay_exports, {
  DEFAULT_WITH_INFO: () => DEFAULT_WITH_INFO,
  DEFAULT_WITH_MAP: () => DEFAULT_WITH_MAP,
  DEFAULT_WITH_TOOLS: () => DEFAULT_WITH_TOOLS,
  MAP: () => MAP,
  ORG_DISPLAY: () => ORG_DISPLAY,
  ORG_DISP_ITEM: () => ORG_DISP_ITEM,
  ORG_DISP_TOOLS_ELEMENT: () => ORG_DISP_TOOLS_ELEMENT,
  ORG_TYPE: () => ORG_TYPE,
  OVERLAY_ALL: () => OVERLAY_ALL,
  OVERLAY_BY: () => OVERLAY_BY,
  OVERLAY_COMPONENT: () => OVERLAY_COMPONENT,
  OVERLAY_FUNCTION: () => OVERLAY_FUNCTION,
  OVERLAY_INDIVIDUAL: () => OVERLAY_INDIVIDUAL,
  OVERLAY_NONE: () => OVERLAY_NONE,
  OVERLAY_STATION: () => OVERLAY_STATION,
  OVERLAY_STATION_COMPONENT: () => OVERLAY_STATION_COMPONENT,
  OVERLAY_VECTOR: () => OVERLAY_VECTOR,
  OrganizedDisplay: () => OrganizedDisplay,
  OrganizedDisplayItem: () => OrganizedDisplayItem,
  OrganizedDisplayTools: () => OrganizedDisplayTools,
  SEISMOGRAPH: () => SEISMOGRAPH,
  WITH_INFO: () => WITH_INFO,
  WITH_MAP: () => WITH_MAP,
  WITH_TOOLS: () => WITH_TOOLS,
  createAttribute: () => createAttribute,
  createPlots: () => createPlots,
  groupComponentOfMotion: () => groupComponentOfMotion,
  individualDisplay: () => individualDisplay,
  mapAndIndividualDisplay: () => mapAndIndividualDisplay,
  overlayAll: () => overlayAll,
  overlayByComponent: () => overlayByComponent,
  overlayBySDDFunction: () => overlayBySDDFunction,
  overlayByStation: () => overlayByStation,
  overlayByStationComponent: () => overlayByStationComponent
});

// src/infotable.mts
var infotable_exports = {};
__export(infotable_exports, {
  CHANNEL_COLUMN: () => CHANNEL_COLUMN,
  CHANNEL_INFO_ELEMENT: () => CHANNEL_INFO_ELEMENT,
  ChannelTable: () => ChannelTable,
  DEFAULT_TEMPLATE: () => DEFAULT_TEMPLATE,
  INFO_ELEMENT: () => INFO_ELEMENT,
  QUAKE_COLUMN: () => QUAKE_COLUMN,
  QUAKE_INFO_ELEMENT: () => QUAKE_INFO_ELEMENT,
  QuakeStationTable: () => QuakeStationTable,
  QuakeTable: () => QuakeTable,
  SDD_INFO_ELEMENT: () => SDD_INFO_ELEMENT,
  SEISMOGRAM_COLUMN: () => SEISMOGRAM_COLUMN,
  STATION_COLUMN: () => STATION_COLUMN,
  STATION_INFO_ELEMENT: () => STATION_INFO_ELEMENT,
  SeismogramTable: () => SeismogramTable,
  StationTable: () => StationTable,
  TABLE_CSS: () => TABLE_CSS,
  depthFormat: () => depthFormat2,
  depthMeterFormat: () => depthMeterFormat2,
  depthNoUnitFormat: () => depthNoUnitFormat2,
  latlonFormat: () => latlonFormat2,
  magFormat: () => magFormat2
});

// src/spelement.mts
var spelement_exports = {};
__export(spelement_exports, {
  SORT_BY: () => SORT_BY,
  SeisPlotElement: () => SeisPlotElement,
  addStyleToElement: () => addStyleToElement
});

// src/seismographconfig.mts
var seismographconfig_exports = {};
__export(seismographconfig_exports, {
  DEFAULT_TITLE: () => DEFAULT_TITLE,
  SeismographConfig: () => SeismographConfig,
  SeismographConfigCache: () => SeismographConfigCache,
  createTimeFormatterForZone: () => createTimeFormatterForZone,
  formatCount: () => formatCount,
  formatCountOrAmp: () => formatCountOrAmp,
  formatExp: () => formatExp,
  numberFormatWrapper: () => numberFormatWrapper
});

// src/cssutil.mts
var cssutil_exports = {};
__export(cssutil_exports, {
  AUTO_CLASSED: () => AUTO_CLASSED,
  AUTO_COLOR_SELECTOR: () => AUTO_COLOR_SELECTOR,
  G_DATA_SELECTOR: () => G_DATA_SELECTOR,
  insertCSS: () => insertCSS,
  isCSSInserted: () => isCSSInserted,
  isIdStyleElement: () => isIdStyleElement
});
var AUTO_CLASSED = "autoseisplotjs";
var AUTO_COLOR_SELECTOR = "seisplotjsautocolor";
var G_DATA_SELECTOR = "seisplotjsdata";
function insertCSS(cssText, id2) {
  const head = document.head;
  if (head === null) {
    throw new Error("document.head is null");
  }
  if (id2) {
    for (const c of Array.from(head.children)) {
      if (isIdStyleElement(c, id2)) {
        document.head.removeChild(c);
      }
    }
  }
  const styleElement = document.createElement("style");
  if (id2) {
    styleElement.id = id2;
  }
  styleElement.type = "text/css";
  styleElement.appendChild(document.createTextNode(cssText));
  head.insertBefore(styleElement, head.firstChild);
  return styleElement;
}
function isCSSInserted(id2) {
  const head = document.head;
  if (head === null) {
    throw new Error("document.head is null");
  }
  for (const c of Array.from(head.children)) {
    if (isIdStyleElement(c, id2)) {
      return true;
    }
  }
  return false;
}
function isIdStyleElement(c, id2) {
  return c.localName === "style" && c.id === id2;
}

// src/seismographutil.mts
var seismographutil_exports = {};
__export(seismographutil_exports, {
  DEFAULT_GRID_LINE_COLOR: () => DEFAULT_GRID_LINE_COLOR,
  DEFAULT_MAX_SAMPLE_PER_PIXEL: () => DEFAULT_MAX_SAMPLE_PER_PIXEL,
  clearCanvas: () => clearCanvas,
  drawAllOnCanvas: () => drawAllOnCanvas,
  drawSeismogramAsLine: () => drawSeismogramAsLine,
  drawXScaleGridLines: () => drawXScaleGridLines,
  drawYScaleGridLines: () => drawYScaleGridLines,
  pushPoint: () => pushPoint,
  rgbaForColorName: () => rgbaForColorName,
  seismogramSegmentAsLine: () => seismogramSegmentAsLine
});

// src/axisutil.mts
var axisutil_exports = {};
__export(axisutil_exports, {
  LuxonTimeScale: () => LuxonTimeScale,
  drawAxisLabels: () => drawAxisLabels,
  drawTitle: () => drawTitle,
  drawXLabel: () => drawXLabel,
  drawXSublabel: () => drawXSublabel,
  drawYLabel: () => drawYLabel,
  drawYSublabel: () => drawYSublabel,
  removeTitle: () => removeTitle,
  removeXLabel: () => removeXLabel,
  removeXSublabel: () => removeXSublabel,
  removeYLabel: () => removeYLabel,
  removeYSublabel: () => removeYSublabel
});

// node_modules/d3-array/src/ascending.js
function ascending(a, b) {
  return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

// node_modules/d3-array/src/descending.js
function descending(a, b) {
  return a == null || b == null ? NaN : b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

// node_modules/d3-array/src/bisector.js
function bisector(f) {
  let compare1, compare2, delta;
  if (f.length !== 2) {
    compare1 = ascending;
    compare2 = (d, x2) => ascending(f(d), x2);
    delta = (d, x2) => f(d) - x2;
  } else {
    compare1 = f === ascending || f === descending ? f : zero;
    compare2 = f;
    delta = f;
  }
  function left2(a, x2, lo = 0, hi = a.length) {
    if (lo < hi) {
      if (compare1(x2, x2) !== 0) return hi;
      do {
        const mid = lo + hi >>> 1;
        if (compare2(a[mid], x2) < 0) lo = mid + 1;
        else hi = mid;
      } while (lo < hi);
    }
    return lo;
  }
  function right2(a, x2, lo = 0, hi = a.length) {
    if (lo < hi) {
      if (compare1(x2, x2) !== 0) return hi;
      do {
        const mid = lo + hi >>> 1;
        if (compare2(a[mid], x2) <= 0) lo = mid + 1;
        else hi = mid;
      } while (lo < hi);
    }
    return lo;
  }
  function center2(a, x2, lo = 0, hi = a.length) {
    const i = left2(a, x2, lo, hi - 1);
    return i > lo && delta(a[i - 1], x2) > -delta(a[i], x2) ? i - 1 : i;
  }
  return { left: left2, center: center2, right: right2 };
}
function zero() {
  return 0;
}

// node_modules/d3-array/src/number.js
function number(x2) {
  return x2 === null ? NaN : +x2;
}

// node_modules/d3-array/src/bisect.js
var ascendingBisect = bisector(ascending);
var bisectRight = ascendingBisect.right;
var bisectLeft = ascendingBisect.left;
var bisectCenter = bisector(number).center;
var bisect_default = bisectRight;

// node_modules/d3-array/src/extent.js
function extent(values, valueof) {
  let min;
  let max;
  if (valueof === void 0) {
    for (const value of values) {
      if (value != null) {
        if (min === void 0) {
          if (value >= value) min = max = value;
        } else {
          if (min > value) min = value;
          if (max < value) max = value;
        }
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null) {
        if (min === void 0) {
          if (value >= value) min = max = value;
        } else {
          if (min > value) min = value;
          if (max < value) max = value;
        }
      }
    }
  }
  return [min, max];
}

// node_modules/d3-array/src/ticks.js
var e10 = Math.sqrt(50);
var e5 = Math.sqrt(10);
var e2 = Math.sqrt(2);
function tickSpec(start2, stop, count) {
  const step = (stop - start2) / Math.max(0, count), power = Math.floor(Math.log10(step)), error51 = step / Math.pow(10, power), factor = error51 >= e10 ? 10 : error51 >= e5 ? 5 : error51 >= e2 ? 2 : 1;
  let i1, i2, inc;
  if (power < 0) {
    inc = Math.pow(10, -power) / factor;
    i1 = Math.round(start2 * inc);
    i2 = Math.round(stop * inc);
    if (i1 / inc < start2) ++i1;
    if (i2 / inc > stop) --i2;
    inc = -inc;
  } else {
    inc = Math.pow(10, power) * factor;
    i1 = Math.round(start2 / inc);
    i2 = Math.round(stop / inc);
    if (i1 * inc < start2) ++i1;
    if (i2 * inc > stop) --i2;
  }
  if (i2 < i1 && 0.5 <= count && count < 2) return tickSpec(start2, stop, count * 2);
  return [i1, i2, inc];
}
function ticks(start2, stop, count) {
  stop = +stop, start2 = +start2, count = +count;
  if (!(count > 0)) return [];
  if (start2 === stop) return [start2];
  const reverse = stop < start2, [i1, i2, inc] = reverse ? tickSpec(stop, start2, count) : tickSpec(start2, stop, count);
  if (!(i2 >= i1)) return [];
  const n2 = i2 - i1 + 1, ticks2 = new Array(n2);
  if (reverse) {
    if (inc < 0) for (let i = 0; i < n2; ++i) ticks2[i] = (i2 - i) / -inc;
    else for (let i = 0; i < n2; ++i) ticks2[i] = (i2 - i) * inc;
  } else {
    if (inc < 0) for (let i = 0; i < n2; ++i) ticks2[i] = (i1 + i) / -inc;
    else for (let i = 0; i < n2; ++i) ticks2[i] = (i1 + i) * inc;
  }
  return ticks2;
}
function tickIncrement(start2, stop, count) {
  stop = +stop, start2 = +start2, count = +count;
  return tickSpec(start2, stop, count)[2];
}
function tickStep(start2, stop, count) {
  stop = +stop, start2 = +start2, count = +count;
  const reverse = stop < start2, inc = reverse ? tickIncrement(stop, start2, count) : tickIncrement(start2, stop, count);
  return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);
}

// node_modules/d3-scale/src/init.js
function initRange(domain2, range) {
  switch (arguments.length) {
    case 0:
      break;
    case 1:
      this.range(domain2);
      break;
    default:
      this.range(range).domain(domain2);
      break;
  }
  return this;
}

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

// node_modules/d3-color/src/color.js
function Color() {
}
var darker = 0.7;
var brighter = 1 / darker;
var reI = "\\s*([+-]?\\d+)\\s*";
var reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*";
var reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*";
var reHex = /^#([0-9a-f]{3,8})$/;
var reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`);
var reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`);
var reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`);
var reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`);
var reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`);
var reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);
var 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
});
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(format2) {
  var m, l2;
  format2 = (format2 + "").trim().toLowerCase();
  return (m = reHex.exec(format2)) ? (l2 = m[1].length, m = parseInt(m[1], 16), l2 === 6 ? rgbn(m) : l2 === 3 ? new Rgb(m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, (m & 15) << 4 | m & 15, 1) : l2 === 8 ? rgba(m >> 24 & 255, m >> 16 & 255, m >> 8 & 255, (m & 255) / 255) : l2 === 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(format2)) ? new Rgb(m[1], m[2], m[3], 1) : (m = reRgbPercent.exec(format2)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) : (m = reRgbaInteger.exec(format2)) ? rgba(m[1], m[2], m[3], m[4]) : (m = reRgbaPercent.exec(format2)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) : (m = reHslPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) : (m = reHslaPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) : named.hasOwnProperty(format2) ? rgbn(named[format2]) : format2 === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null;
}
function rgbn(n2) {
  return new Rgb(n2 >> 16 & 255, n2 >> 8 & 255, n2 & 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;
}
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
}));
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, s2, l2, a) {
  if (a <= 0) h = s2 = l2 = NaN;
  else if (l2 <= 0 || l2 >= 1) h = s2 = NaN;
  else if (s2 <= 0) h = NaN;
  return new Hsl(h, s2, l2, 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, s2 = max - min, l2 = (max + min) / 2;
  if (s2) {
    if (r === max) h = (g - b) / s2 + (g < b) * 6;
    else if (g === max) h = (b - r) / s2 + 2;
    else h = (r - g) / s2 + 4;
    s2 /= l2 < 0.5 ? max + min : 2 - max - min;
    h *= 60;
  } else {
    s2 = l2 > 0 && l2 < 1 ? 0 : h;
  }
  return new Hsl(h, s2, l2, o.opacity);
}
function hsl(h, s2, l2, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s2, l2, opacity == null ? 1 : opacity);
}
function Hsl(h, s2, l2, opacity) {
  this.h = +h;
  this.s = +s2;
  this.l = +l2;
  this.opacity = +opacity;
}
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, s2 = isNaN(h) || isNaN(this.s) ? 0 : this.s, l2 = this.l, m2 = l2 + (l2 < 0.5 ? l2 : 1 - l2) * s2, m1 = 2 * l2 - 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})`}`;
  }
}));
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;
}

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

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

// node_modules/d3-interpolate/src/constant.js
var constant_default = (x2) => () => x2;

// node_modules/d3-interpolate/src/color.js
function linear(a, d) {
  return function(t) {
    return a + t * d;
  };
}
function exponential(a, b, y2) {
  return a = Math.pow(a, y2), b = Math.pow(b, y2) - a, y2 = 1 / y2, function(t) {
    return Math.pow(a + t * b, y2);
  };
}
function gamma(y2) {
  return (y2 = +y2) === 1 ? nogamma : function(a, b) {
    return b - a ? exponential(a, b, y2) : 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);
}

// node_modules/d3-interpolate/src/rgb.js
var rgb_default = (function rgbGamma(y2) {
  var color2 = gamma(y2);
  function rgb2(start2, end) {
    var r = color2((start2 = rgb(start2)).r, (end = rgb(end)).r), g = color2(start2.g, end.g), b = color2(start2.b, end.b), opacity = nogamma(start2.opacity, end.opacity);
    return function(t) {
      start2.r = r(t);
      start2.g = g(t);
      start2.b = b(t);
      start2.opacity = opacity(t);
      return start2 + "";
    };
  }
  rgb2.gamma = rgbGamma;
  return rgb2;
})(1);
function rgbSpline(spline) {
  return function(colors) {
    var n2 = colors.length, r = new Array(n2), g = new Array(n2), b = new Array(n2), i, color2;
    for (i = 0; i < n2; ++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 rgbBasis = rgbSpline(basis_default);
var rgbBasisClosed = rgbSpline(basisClosed_default);

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

// node_modules/d3-interpolate/src/array.js
function genericArray(a, b) {
  var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x2 = new Array(na), c = new Array(nb), i;
  for (i = 0; i < na; ++i) x2[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] = x2[i](t);
    return c;
  };
}

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

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

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

// node_modules/d3-interpolate/src/string.js
var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
var reB = new RegExp(reA.source, "g");
function zero2(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, s2 = [], 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 (s2[i]) s2[i] += bs;
      else s2[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) {
      if (s2[i]) s2[i] += bm;
      else s2[++i] = bm;
    } else {
      s2[++i] = null;
      q.push({ i, x: number_default(am, bm) });
    }
    bi = reB.lastIndex;
  }
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s2[i]) s2[i] += bs;
    else s2[++i] = bs;
  }
  return s2.length < 2 ? q[0] ? one(q[0].x) : zero2(b) : (b = q.length, function(t) {
    for (var i2 = 0, o; i2 < b; ++i2) s2[(o = q[i2]).i] = o.x(t);
    return s2.join("");
  });
}

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

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

// node_modules/d3-interpolate/src/transform/decompose.js
var degrees = 180 / Math.PI;
var identity = {
  translateX: 0,
  translateY: 0,
  rotate: 0,
  skewX: 0,
  scaleX: 1,
  scaleY: 1
};
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) * degrees,
    skewX: Math.atan(skewX) * degrees,
    scaleX,
    scaleY
  };
}

// node_modules/d3-interpolate/src/transform/parse.js
var svgNode;
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);
}

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

// node_modules/d3-scale/src/constant.js
function constants(x2) {
  return function() {
    return x2;
  };
}

// node_modules/d3-scale/src/number.js
function number2(x2) {
  return +x2;
}

// node_modules/d3-scale/src/continuous.js
var unit = [0, 1];
function identity2(x2) {
  return x2;
}
function normalize(a, b) {
  return (b -= a = +a) ? function(x2) {
    return (x2 - a) / b;
  } : constants(isNaN(b) ? NaN : 0.5);
}
function clamper(a, b) {
  var t;
  if (a > b) t = a, a = b, b = t;
  return function(x2) {
    return Math.max(a, Math.min(b, x2));
  };
}
function bimap(domain2, range, interpolate) {
  var d0 = domain2[0], d1 = domain2[1], r0 = range[0], r1 = range[1];
  if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate(r1, r0);
  else d0 = normalize(d0, d1), r0 = interpolate(r0, r1);
  return function(x2) {
    return r0(d0(x2));
  };
}
function polymap(domain2, range, interpolate) {
  var j = Math.min(domain2.length, range.length) - 1, d = new Array(j), r = new Array(j), i = -1;
  if (domain2[j] < domain2[0]) {
    domain2 = domain2.slice().reverse();
    range = range.slice().reverse();
  }
  while (++i < j) {
    d[i] = normalize(domain2[i], domain2[i + 1]);
    r[i] = interpolate(range[i], range[i + 1]);
  }
  return function(x2) {
    var i2 = bisect_default(domain2, x2, 1, j) - 1;
    return r[i2](d[i2](x2));
  };
}
function copy(source, target) {
  return target.domain(source.domain()).range(source.range()).interpolate(source.interpolate()).clamp(source.clamp()).unknown(source.unknown());
}
function transformer() {
  var domain2 = unit, range = unit, interpolate = value_default, transform2, untransform, unknown2, clamp = identity2, piecewise, output, input;
  function rescale() {
    var n2 = Math.min(domain2.length, range.length);
    if (clamp !== identity2) clamp = clamper(domain2[0], domain2[n2 - 1]);
    piecewise = n2 > 2 ? polymap : bimap;
    output = input = null;
    return scale;
  }
  function scale(x2) {
    return x2 == null || isNaN(x2 = +x2) ? unknown2 : (output || (output = piecewise(domain2.map(transform2), range, interpolate)))(transform2(clamp(x2)));
  }
  scale.invert = function(y2) {
    return clamp(untransform((input || (input = piecewise(range, domain2.map(transform2), number_default)))(y2)));
  };
  scale.domain = function(_) {
    return arguments.length ? (domain2 = Array.from(_, number2), rescale()) : domain2.slice();
  };
  scale.range = function(_) {
    return arguments.length ? (range = Array.from(_), rescale()) : range.slice();
  };
  scale.rangeRound = function(_) {
    return range = Array.from(_), interpolate = round_default, rescale();
  };
  scale.clamp = function(_) {
    return arguments.length ? (clamp = _ ? true : identity2, rescale()) : clamp !== identity2;
  };
  scale.interpolate = function(_) {
    return arguments.length ? (interpolate = _, rescale()) : interpolate;
  };
  scale.unknown = function(_) {
    return arguments.length ? (unknown2 = _, scale) : unknown2;
  };
  return function(t, u) {
    transform2 = t, untransform = u;
    return rescale();
  };
}
function continuous() {
  return transformer()(identity2, identity2);
}

// node_modules/d3-format/src/formatDecimal.js
function formatDecimal_default(x2) {
  return Math.abs(x2 = Math.round(x2)) >= 1e21 ? x2.toLocaleString("en").replace(/,/g, "") : x2.toString(10);
}
function formatDecimalParts(x2, p) {
  if (!isFinite(x2) || x2 === 0) return null;
  var i = (x2 = p ? x2.toExponential(p - 1) : x2.toExponential()).indexOf("e"), coefficient = x2.slice(0, i);
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x2.slice(i + 1)
  ];
}

// node_modules/d3-format/src/exponent.js
function exponent_default(x2) {
  return x2 = formatDecimalParts(Math.abs(x2)), x2 ? x2[1] : NaN;
}

// node_modules/d3-format/src/formatGroup.js
function formatGroup_default(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);
  };
}

// node_modules/d3-format/src/formatNumerals.js
function formatNumerals_default(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i) {
      return numerals[+i];
    });
  };
}

// node_modules/d3-format/src/formatSpecifier.js
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
function formatSpecifier(specifier) {
  if (!(match2 = re.exec(specifier))) throw new Error("invalid format: " + specifier);
  var match2;
  return new FormatSpecifier({
    fill: match2[1],
    align: match2[2],
    sign: match2[3],
    symbol: match2[4],
    zero: match2[5],
    width: match2[6],
    comma: match2[7],
    precision: match2[8] && match2[8].slice(1),
    trim: match2[9],
    type: match2[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;
};

// node_modules/d3-format/src/formatTrim.js
function formatTrim_default(s2) {
  out: for (var n2 = s2.length, i = 1, i0 = -1, i1; i < n2; ++i) {
    switch (s2[i]) {
      case ".":
        i0 = i1 = i;
        break;
      case "0":
        if (i0 === 0) i0 = i;
        i1 = i;
        break;
      default:
        if (!+s2[i]) break out;
        if (i0 > 0) i0 = 0;
        break;
    }
  }
  return i0 > 0 ? s2.slice(0, i0) + s2.slice(i1 + 1) : s2;
}

// node_modules/d3-format/src/formatPrefixAuto.js
var prefixExponent;
function formatPrefixAuto_default(x2, p) {
  var d = formatDecimalParts(x2, p);
  if (!d) return prefixExponent = void 0, x2.toPrecision(p);
  var coefficient = d[0], exponent = d[1], i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1, n2 = coefficient.length;
  return i === n2 ? coefficient : i > n2 ? coefficient + new Array(i - n2 + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimalParts(x2, Math.max(0, p + i - 1))[0];
}

// node_modules/d3-format/src/formatRounded.js
function formatRounded_default(x2, p) {
  var d = formatDecimalParts(x2, p);
  if (!d) return x2 + "";
  var coefficient = d[0], exponent = d[1];
  return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1) : coefficient + new Array(exponent - coefficient.length + 2).join("0");
}

// node_modules/d3-format/src/formatTypes.js
var formatTypes_default = {
  "%": (x2, p) => (x2 * 100).toFixed(p),
  "b": (x2) => Math.round(x2).toString(2),
  "c": (x2) => x2 + "",
  "d": formatDecimal_default,
  "e": (x2, p) => x2.toExponential(p),
  "f": (x2, p) => x2.toFixed(p),
  "g": (x2, p) => x2.toPrecision(p),
  "o": (x2) => Math.round(x2).toString(8),
  "p": (x2, p) => formatRounded_default(x2 * 100, p),
  "r": formatRounded_default,
  "s": formatPrefixAuto_default,
  "X": (x2) => Math.round(x2).toString(16).toUpperCase(),
  "x": (x2) => Math.round(x2).toString(16)
};

// node_modules/d3-format/src/identity.js
function identity_default(x2) {
  return x2;
}

// node_modules/d3-format/src/locale.js
var map = Array.prototype.map;
var prefixes = ["y", "z", "a", "f", "p", "n", "\xB5", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"];
function locale_default(locale3) {
  var group = locale3.grouping === void 0 || locale3.thousands === void 0 ? identity_default : formatGroup_default(map.call(locale3.grouping, Number), locale3.thousands + ""), currencyPrefix = locale3.currency === void 0 ? "" : locale3.currency[0] + "", currencySuffix = locale3.currency === void 0 ? "" : locale3.currency[1] + "", decimal = locale3.decimal === void 0 ? "." : locale3.decimal + "", numerals = locale3.numerals === void 0 ? identity_default : formatNumerals_default(map.call(locale3.numerals, String)), percent = locale3.percent === void 0 ? "%" : locale3.percent + "", minus = locale3.minus === void 0 ? "\u2212" : locale3.minus + "", nan2 = locale3.nan === void 0 ? "NaN" : locale3.nan + "";
  function newFormat(specifier, options) {
    specifier = formatSpecifier(specifier);
    var fill = specifier.fill, align = specifier.align, sign = specifier.sign, symbol2 = specifier.symbol, zero3 = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim2 = specifier.trim, type = specifier.type;
    if (type === "n") comma = true, type = "g";
    else if (!formatTypes_default[type]) precision === void 0 && (precision = 12), trim2 = true, type = "g";
    if (zero3 || fill === "0" && align === "=") zero3 = true, fill = "0", align = "=";
    var prefix = (options && options.prefix !== void 0 ? options.prefix : "") + (symbol2 === "$" ? currencyPrefix : symbol2 === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : ""), suffix = (symbol2 === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "") + (options && options.suffix !== void 0 ? options.suffix : "");
    var formatType = formatTypes_default[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 format2(value) {
      var valuePrefix = prefix, valueSuffix = suffix, i, n2, c;
      if (type === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;
        var valueNegative = value < 0 || 1 / value < 0;
        value = isNaN(value) ? nan2 : formatType(Math.abs(value), precision);
        if (trim2) value = formatTrim_default(value);
        if (valueNegative && +value === 0 && sign !== "+") valueNegative = false;
        valuePrefix = (valueNegative ? sign === "(" ? sign : minus : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
        valueSuffix = (type === "s" && !isNaN(value) && prefixExponent !== void 0 ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
        if (maybeSuffix) {
          i = -1, n2 = value.length;
          while (++i < n2) {
            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 && !zero3) value = group(value, Infinity);
      var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : "";
      if (comma && zero3) 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);
    }
    format2.toString = function() {
      return specifier + "";
    };
    return format2;
  }
  function formatPrefix2(specifier, value) {
    var e = Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3, k = Math.pow(10, -e), f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier), { suffix: prefixes[8 + e / 3] });
    return function(value2) {
      return f(k * value2);
    };
  }
  return {
    format: newFormat,
    formatPrefix: formatPrefix2
  };
}

// node_modules/d3-format/src/defaultLocale.js
var locale;
var format;
var formatPrefix;
defaultLocale2({
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});
function defaultLocale2(definition) {
  locale = locale_default(definition);
  format = locale.format;
  formatPrefix = locale.formatPrefix;
  return locale;
}

// node_modules/d3-format/src/precisionFixed.js
function precisionFixed_default(step) {
  return Math.max(0, -exponent_default(Math.abs(step)));
}

// node_modules/d3-format/src/precisionPrefix.js
function precisionPrefix_default(step, value) {
  return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3 - exponent_default(Math.abs(step)));
}

// node_modules/d3-format/src/precisionRound.js
function precisionRound_default(step, max) {
  step = Math.abs(step), max = Math.abs(max) - step;
  return Math.max(0, exponent_default(max) - exponent_default(step)) + 1;
}

// node_modules/d3-scale/src/tickFormat.js
function tickFormat(start2, stop, count, specifier) {
  var step = tickStep(start2, stop, count), precision;
  specifier = formatSpecifier(specifier == null ? ",f" : specifier);
  switch (specifier.type) {
    case "s": {
      var value = Math.max(Math.abs(start2), Math.abs(stop));
      if (specifier.precision == null && !isNaN(precision = precisionPrefix_default(step, value))) specifier.precision = precision;
      return formatPrefix(specifier, value);
    }
    case "":
    case "e":
    case "g":
    case "p":
    case "r": {
      if (specifier.precision == null && !isNaN(precision = precisionRound_default(step, Math.max(Math.abs(start2), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e");
      break;
    }
    case "f":
    case "%": {
      if (specifier.precision == null && !isNaN(precision = precisionFixed_default(step))) specifier.precision = precision - (specifier.type === "%") * 2;
      break;
    }
  }
  return format(specifier);
}

// node_modules/d3-scale/src/linear.js
function linearish(scale) {
  var domain2 = scale.domain;
  scale.ticks = function(count) {
    var d = domain2();
    return ticks(d[0], d[d.length - 1], count == null ? 10 : count);
  };
  scale.tickFormat = function(count, specifier) {
    var d = domain2();
    return tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);
  };
  scale.nice = function(count) {
    if (count == null) count = 10;
    var d = domain2();
    var i0 = 0;
    var i1 = d.length - 1;
    var start2 = d[i0];
    var stop = d[i1];
    var prestep;
    var step;
    var maxIter = 10;
    if (stop < start2) {
      step = start2, start2 = stop, stop = step;
      step = i0, i0 = i1, i1 = step;
    }
    while (maxIter-- > 0) {
      step = tickIncrement(start2, stop, count);
      if (step === prestep) {
        d[i0] = start2;
        d[i1] = stop;
        return domain2(d);
      } else if (step > 0) {
        start2 = Math.floor(start2 / step) * step;
        stop = Math.ceil(stop / step) * step;
      } else if (step < 0) {
        start2 = Math.ceil(start2 * step) / step;
        stop = Math.floor(stop * step) / step;
      } else {
        break;
      }
      prestep = step;
    }
    return scale;
  };
  return scale;
}
function linear2() {
  var scale = continuous();
  scale.copy = function() {
    return copy(scale, linear2());
  };
  initRange.apply(scale, arguments);
  return linearish(scale);
}

// node_modules/d3-scale/src/nice.js
function nice(domain2, interval2) {
  domain2 = domain2.slice();
  var i0 = 0, i1 = domain2.length - 1, x0 = domain2[i0], x1 = domain2[i1], t;
  if (x1 < x0) {
    t = i0, i0 = i1, i1 = t;
    t = x0, x0 = x1, x1 = t;
  }
  domain2[i0] = interval2.floor(x0);
  domain2[i1] = interval2.ceil(x1);
  return domain2;
}

// node_modules/d3-scale/src/log.js
function transformLog(x2) {
  return Math.log(x2);
}
function transformExp(x2) {
  return Math.exp(x2);
}
function transformLogn(x2) {
  return -Math.log(-x2);
}
function transformExpn(x2) {
  return -Math.exp(-x2);
}
function pow10(x2) {
  return isFinite(x2) ? +("1e" + x2) : x2 < 0 ? 0 : x2;
}
function powp(base) {
  return base === 10 ? pow10 : base === Math.E ? Math.exp : (x2) => Math.pow(base, x2);
}
function logp(base) {
  return base === Math.E ? Math.log : base === 10 && Math.log10 || base === 2 && Math.log2 || (base = Math.log(base), (x2) => Math.log(x2) / base);
}
function reflect(f) {
  return (x2, k) => -f(-x2, k);
}
function loggish(transform2) {
  const scale = transform2(transformLog, transformExp);
  const domain2 = scale.domain;
  let base = 10;
  let logs;
  let pows;
  function rescale() {
    logs = logp(base), pows = powp(base);
    if (domain2()[0] < 0) {
      logs = reflect(logs), pows = reflect(pows);
      transform2(transformLogn, transformExpn);
    } else {
      transform2(transformLog, transformExp);
    }
    return scale;
  }
  scale.base = function(_) {
    return arguments.length ? (base = +_, rescale()) : base;
  };
  scale.domain = function(_) {
    return arguments.length ? (domain2(_), rescale()) : domain2();
  };
  scale.ticks = (count) => {
    const d = domain2();
    let u = d[0];
    let v = d[d.length - 1];
    const r = v < u;
    if (r) [u, v] = [v, u];
    let i = logs(u);
    let j = logs(v);
    let k;
    let t;
    const n2 = count == null ? 10 : +count;
    let z2 = [];
    if (!(base % 1) && j - i < n2) {
      i = Math.floor(i), j = Math.ceil(j);
      if (u > 0) for (; i <= j; ++i) {
        for (k = 1; k < base; ++k) {
          t = i < 0 ? k / pows(-i) : k * pows(i);
          if (t < u) continue;
          if (t > v) break;
          z2.push(t);
        }
      }
      else for (; i <= j; ++i) {
        for (k = base - 1; k >= 1; --k) {
          t = i > 0 ? k / pows(-i) : k * pows(i);
          if (t < u) continue;
          if (t > v) break;
          z2.push(t);
        }
      }
      if (z2.length * 2 < n2) z2 = ticks(u, v, n2);
    } else {
      z2 = ticks(i, j, Math.min(j - i, n2)).map(pows);
    }
    return r ? z2.reverse() : z2;
  };
  scale.tickFormat = (count, specifier) => {
    if (count == null) count = 10;
    if (specifier == null) specifier = base === 10 ? "s" : ",";
    if (typeof specifier !== "function") {
      if (!(base % 1) && (specifier = formatSpecifier(specifier)).precision == null) specifier.trim = true;
      specifier = format(specifier);
    }
    if (count === Infinity) return specifier;
    const k = Math.max(1, base * count / scale.ticks().length);
    return (d) => {
      let i = d / pows(Math.round(logs(d)));
      if (i * base < base - 0.5) i *= base;
      return i <= k ? specifier(d) : "";
    };
  };
  scale.nice = () => {
    return domain2(nice(domain2(), {
      floor: (x2) => pows(Math.floor(logs(x2))),
      ceil: (x2) => pows(Math.ceil(logs(x2)))
    }));
  };
  return scale;
}
function log2() {
  const scale = loggish(transformer()).domain([1, 10]);
  scale.copy = () => copy(scale, log2()).base(scale.base());
  initRange.apply(scale, arguments);
  return scale;
}

// node_modules/d3-time/src/interval.js
var t0 = /* @__PURE__ */ new Date();
var t1 = /* @__PURE__ */ new Date();
function timeInterval(floori, offseti, count, field) {
  function interval2(date6) {
    return floori(date6 = arguments.length === 0 ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date(+date6)), date6;
  }
  interval2.floor = (date6) => {
    return floori(date6 = /* @__PURE__ */ new Date(+date6)), date6;
  };
  interval2.ceil = (date6) => {
    return floori(date6 = new Date(date6 - 1)), offseti(date6, 1), floori(date6), date6;
  };
  interval2.round = (date6) => {
    const d0 = interval2(date6), d1 = interval2.ceil(date6);
    return date6 - d0 < d1 - date6 ? d0 : d1;
  };
  interval2.offset = (date6, step) => {
    return offseti(date6 = /* @__PURE__ */ new Date(+date6), step == null ? 1 : Math.floor(step)), date6;
  };
  interval2.range = (start2, stop, step) => {
    const range = [];
    start2 = interval2.ceil(start2);
    step = step == null ? 1 : Math.floor(step);
    if (!(start2 < stop) || !(step > 0)) return range;
    let previous;
    do
      range.push(previous = /* @__PURE__ */ new Date(+start2)), offseti(start2, step), floori(start2);
    while (previous < start2 && start2 < stop);
    return range;
  };
  interval2.filter = (test) => {
    return timeInterval((date6) => {
      if (date6 >= date6) while (floori(date6), !test(date6)) date6.setTime(date6 - 1);
    }, (date6, step) => {
      if (date6 >= date6) {
        if (step < 0) while (++step <= 0) {
          while (offseti(date6, -1), !test(date6)) {
          }
        }
        else while (--step >= 0) {
          while (offseti(date6, 1), !test(date6)) {
          }
        }
      }
    });
  };
  if (count) {
    interval2.count = (start2, end) => {
      t0.setTime(+start2), t1.setTime(+end);
      floori(t0), floori(t1);
      return Math.floor(count(t0, t1));
    };
    interval2.every = (step) => {
      step = Math.floor(step);
      return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval2 : interval2.filter(field ? (d) => field(d) % step === 0 : (d) => interval2.count(0, d) % step === 0);
    };
  }
  return interval2;
}

// node_modules/d3-time/src/millisecond.js
var millisecond = timeInterval(() => {
}, (date6, step) => {
  date6.setTime(+date6 + step);
}, (start2, end) => {
  return end - start2;
});
millisecond.every = (k) => {
  k = Math.floor(k);
  if (!isFinite(k) || !(k > 0)) return null;
  if (!(k > 1)) return millisecond;
  return timeInterval((date6) => {
    date6.setTime(Math.floor(date6 / k) * k);
  }, (date6, step) => {
    date6.setTime(+date6 + step * k);
  }, (start2, end) => {
    return (end - start2) / k;
  });
};
var milliseconds = millisecond.range;

// node_modules/d3-time/src/duration.js
var durationSecond = 1e3;
var durationMinute = durationSecond * 60;
var durationHour = durationMinute * 60;
var durationDay = durationHour * 24;
var durationWeek = durationDay * 7;
var durationMonth = durationDay * 30;
var durationYear = durationDay * 365;

// node_modules/d3-time/src/second.js
var second = timeInterval((date6) => {
  date6.setTime(date6 - date6.getMilliseconds());
}, (date6, step) => {
  date6.setTime(+date6 + step * durationSecond);
}, (start2, end) => {
  return (end - start2) / durationSecond;
}, (date6) => {
  return date6.getUTCSeconds();
});
var seconds = second.range;

// node_modules/d3-time/src/minute.js
var timeMinute = timeInterval((date6) => {
  date6.setTime(date6 - date6.getMilliseconds() - date6.getSeconds() * durationSecond);
}, (date6, step) => {
  date6.setTime(+date6 + step * durationMinute);
}, (start2, end) => {
  return (end - start2) / durationMinute;
}, (date6) => {
  return date6.getMinutes();
});
var timeMinutes = timeMinute.range;
var utcMinute = timeInterval((date6) => {
  date6.setUTCSeconds(0, 0);
}, (date6, step) => {
  date6.setTime(+date6 + step * durationMinute);
}, (start2, end) => {
  return (end - start2) / durationMinute;
}, (date6) => {
  return date6.getUTCMinutes();
});
var utcMinutes = utcMinute.range;

// node_modules/d3-time/src/hour.js
var timeHour = timeInterval((date6) => {
  date6.setTime(date6 - date6.getMilliseconds() - date6.getSeconds() * durationSecond - date6.getMinutes() * durationMinute);
}, (date6, step) => {
  date6.setTime(+date6 + step * durationHour);
}, (start2, end) => {
  return (end - start2) / durationHour;
}, (date6) => {
  return date6.getHours();
});
var timeHours = timeHour.range;
var utcHour = timeInterval((date6) => {
  date6.setUTCMinutes(0, 0, 0);
}, (date6, step) => {
  date6.setTime(+date6 + step * durationHour);
}, (start2, end) => {
  return (end - start2) / durationHour;
}, (date6) => {
  return date6.getUTCHours();
});
var utcHours = utcHour.range;

// node_modules/d3-time/src/day.js
var timeDay = timeInterval(
  (date6) => date6.setHours(0, 0, 0, 0),
  (date6, step) => date6.setDate(date6.getDate() + step),
  (start2, end) => (end - start2 - (end.getTimezoneOffset() - start2.getTimezoneOffset()) * durationMinute) / durationDay,
  (date6) => date6.getDate() - 1
);
var timeDays = timeDay.range;
var utcDay = timeInterval((date6) => {
  date6.setUTCHours(0, 0, 0, 0);
}, (date6, step) => {
  date6.setUTCDate(date6.getUTCDate() + step);
}, (start2, end) => {
  return (end - start2) / durationDay;
}, (date6) => {
  return date6.getUTCDate() - 1;
});
var utcDays = utcDay.range;
var unixDay = timeInterval((date6) => {
  date6.setUTCHours(0, 0, 0, 0);
}, (date6, step) => {
  date6.setUTCDate(date6.getUTCDate() + step);
}, (start2, end) => {
  return (end - start2) / durationDay;
}, (date6) => {
  return Math.floor(date6 / durationDay);
});
var unixDays = unixDay.range;

// node_modules/d3-time/src/week.js
function timeWeekday(i) {
  return timeInterval((date6) => {
    date6.setDate(date6.getDate() - (date6.getDay() + 7 - i) % 7);
    date6.setHours(0, 0, 0, 0);
  }, (date6, step) => {
    date6.setDate(date6.getDate() + step * 7);
  }, (start2, end) => {
    return (end - start2 - (end.getTimezoneOffset() - start2.getTimezoneOffset()) * durationMinute) / durationWeek;
  });
}
var timeSunday = timeWeekday(0);
var timeMonday = timeWeekday(1);
var timeTuesday = timeWeekday(2);
var timeWednesday = timeWeekday(3);
var timeThursday = timeWeekday(4);
var timeFriday = timeWeekday(5);
var timeSaturday = timeWeekday(6);
var timeSundays = timeSunday.range;
var timeMondays = timeMonday.range;
var timeTuesdays = timeTuesday.range;
var timeWednesdays = timeWednesday.range;
var timeThursdays = timeThursday.range;
var timeFridays = timeFriday.range;
var timeSaturdays = timeSaturday.range;
function utcWeekday(i) {
  return timeInterval((date6) => {
    date6.setUTCDate(date6.getUTCDate() - (date6.getUTCDay() + 7 - i) % 7);
    date6.setUTCHours(0, 0, 0, 0);
  }, (date6, step) => {
    date6.setUTCDate(date6.getUTCDate() + step * 7);
  }, (start2, end) => {
    return (end - start2) / 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;

// node_modules/d3-time/src/month.js
var timeMonth = timeInterval((date6) => {
  date6.setDate(1);
  date6.setHours(0, 0, 0, 0);
}, (date6, step) => {
  date6.setMonth(date6.getMonth() + step);
}, (start2, end) => {
  return end.getMonth() - start2.getMonth() + (end.getFullYear() - start2.getFullYear()) * 12;
}, (date6) => {
  return date6.getMonth();
});
var timeMonths = timeMonth.range;
var utcMonth = timeInterval((date6) => {
  date6.setUTCDate(1);
  date6.setUTCHours(0, 0, 0, 0);
}, (date6, step) => {
  date6.setUTCMonth(date6.getUTCMonth() + step);
}, (start2, end) => {
  return end.getUTCMonth() - start2.getUTCMonth() + (end.getUTCFullYear() - start2.getUTCFullYear()) * 12;
}, (date6) => {
  return date6.getUTCMonth();
});
var utcMonths = utcMonth.range;

// node_modules/d3-time/src/year.js
var timeYear = timeInterval((date6) => {
  date6.setMonth(0, 1);
  date6.setHours(0, 0, 0, 0);
}, (date6, step) => {
  date6.setFullYear(date6.getFullYear() + step);
}, (start2, end) => {
  return end.getFullYear() - start2.getFullYear();
}, (date6) => {
  return date6.getFullYear();
});
timeYear.every = (k) => {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date6) => {
    date6.setFullYear(Math.floor(date6.getFullYear() / k) * k);
    date6.setMonth(0, 1);
    date6.setHours(0, 0, 0, 0);
  }, (date6, step) => {
    date6.setFullYear(date6.getFullYear() + step * k);
  });
};
var timeYears = timeYear.range;
var utcYear = timeInterval((date6) => {
  date6.setUTCMonth(0, 1);
  date6.setUTCHours(0, 0, 0, 0);
}, (date6, step) => {
  date6.setUTCFullYear(date6.getUTCFullYear() + step);
}, (start2, end) => {
  return end.getUTCFullYear() - start2.getUTCFullYear();
}, (date6) => {
  return date6.getUTCFullYear();
});
utcYear.every = (k) => {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date6) => {
    date6.setUTCFullYear(Math.floor(date6.getUTCFullYear() / k) * k);
    date6.setUTCMonth(0, 1);
    date6.setUTCHours(0, 0, 0, 0);
  }, (date6, step) => {
    date6.setUTCFullYear(date6.getUTCFullYear() + step * k);
  });
};
var utcYears = utcYear.range;

// node_modules/d3-time/src/ticks.js
function ticker(year, month, week, day, hour, minute) {
  const tickIntervals = [
    [second, 1, durationSecond],
    [second, 5, 5 * durationSecond],
    [second, 15, 15 * durationSecond],
    [second, 30, 30 * durationSecond],
    [minute, 1, durationMinute],
    [minute, 5, 5 * durationMinute],
    [minute, 15, 15 * durationMinute],
    [minute, 30, 30 * durationMinute],
    [hour, 1, durationHour],
    [hour, 3, 3 * durationHour],
    [hour, 6, 6 * durationHour],
    [hour, 12, 12 * durationHour],
    [day, 1, durationDay],
    [day, 2, 2 * durationDay],
    [week, 1, durationWeek],
    [month, 1, durationMonth],
    [month, 3, 3 * durationMonth],
    [year, 1, durationYear]
  ];
  function ticks2(start2, stop, count) {
    const reverse = stop < start2;
    if (reverse) [start2, stop] = [stop, start2];
    const interval2 = count && typeof count.range === "function" ? count : tickInterval(start2, stop, count);
    const ticks3 = interval2 ? interval2.range(start2, +stop + 1) : [];
    return reverse ? ticks3.reverse() : ticks3;
  }
  function tickInterval(start2, stop, count) {
    const target = Math.abs(stop - start2) / count;
    const i = bisector(([, , step2]) => step2).right(tickIntervals, target);
    if (i === tickIntervals.length) return year.every(tickStep(start2 / durationYear, stop / durationYear, count));
    if (i === 0) return millisecond.every(Math.max(tickStep(start2, stop, count), 1));
    const [t, step] = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];
    return t.every(step);
  }
  return [ticks2, tickInterval];
}
var [utcTicks, utcTickInterval] = ticker(utcYear, utcMonth, utcSunday, unixDay, utcHour, utcMinute);
var [timeTicks, timeTickInterval] = ticker(timeYear, timeMonth, timeSunday, timeDay, timeHour, timeMinute);

// node_modules/d3-time-format/src/locale.js
function localDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date6 = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
    date6.setFullYear(d.y);
    return date6;
  }
  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 date6 = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
    date6.setUTCFullYear(d.y);
    return date6;
  }
  return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function newDate(y2, m, d) {
  return { y: y2, m, d, H: 0, M: 0, S: 0, L: 0 };
}
function formatLocale(locale3) {
  var locale_dateTime = locale3.dateTime, locale_date = locale3.date, locale_time = locale3.time, locale_periods = locale3.periods, locale_weekdays = locale3.days, locale_shortWeekdays = locale3.shortDays, locale_months = locale3.months, locale_shortMonths = locale3.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,
    "g": formatYearISO,
    "G": formatFullYearISO,
    "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,
    "g": formatUTCYearISO,
    "G": formatUTCFullYearISO,
    "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,
    "g": parseYear,
    "G": parseFullYear,
    "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(date6) {
      var string4 = [], i = -1, j = 0, n2 = specifier.length, c, pad3, format2;
      if (!(date6 instanceof Date)) date6 = /* @__PURE__ */ new Date(+date6);
      while (++i < n2) {
        if (specifier.charCodeAt(i) === 37) {
          string4.push(specifier.slice(j, i));
          if ((pad3 = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);
          else pad3 = c === "e" ? " " : "0";
          if (format2 = formats2[c]) c = format2(date6, pad3);
          string4.push(c);
          j = i + 1;
        }
      }
      string4.push(specifier.slice(j, i));
      return string4.join("");
    };
  }
  function newParse(specifier, Z) {
    return function(string4) {
      var d = newDate(1900, void 0, 1), i = parseSpecifier(d, specifier, string4 += "", 0), week, day;
      if (i != string4.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 ? utcMonday.ceil(week) : utcMonday(week);
          week = 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 ? timeMonday.ceil(week) : timeMonday(week);
          week = 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, string4, j) {
    var i = 0, n2 = specifier.length, m = string4.length, c, parse5;
    while (i < n2) {
      if (j >= m) return -1;
      c = specifier.charCodeAt(i++);
      if (c === 37) {
        c = specifier.charAt(i++);
        parse5 = parses[c in pads ? specifier.charAt(i++) : c];
        if (!parse5 || (j = parse5(d, string4, j)) < 0) return -1;
      } else if (c != string4.charCodeAt(j++)) {
        return -1;
      }
    }
    return j;
  }
  function parsePeriod(d, string4, i) {
    var n2 = periodRe.exec(string4.slice(i));
    return n2 ? (d.p = periodLookup.get(n2[0].toLowerCase()), i + n2[0].length) : -1;
  }
  function parseShortWeekday(d, string4, i) {
    var n2 = shortWeekdayRe.exec(string4.slice(i));
    return n2 ? (d.w = shortWeekdayLookup.get(n2[0].toLowerCase()), i + n2[0].length) : -1;
  }
  function parseWeekday(d, string4, i) {
    var n2 = weekdayRe.exec(string4.slice(i));
    return n2 ? (d.w = weekdayLookup.get(n2[0].toLowerCase()), i + n2[0].length) : -1;
  }
  function parseShortMonth(d, string4, i) {
    var n2 = shortMonthRe.exec(string4.slice(i));
    return n2 ? (d.m = shortMonthLookup.get(n2[0].toLowerCase()), i + n2[0].length) : -1;
  }
  function parseMonth(d, string4, i) {
    var n2 = monthRe.exec(string4.slice(i));
    return n2 ? (d.m = monthLookup.get(n2[0].toLowerCase()), i + n2[0].length) : -1;
  }
  function parseLocaleDateTime(d, string4, i) {
    return parseSpecifier(d, locale_dateTime, string4, i);
  }
  function parseLocaleDate(d, string4, i) {
    return parseSpecifier(d, locale_date, string4, i);
  }
  function parseLocaleTime(d, string4, i) {
    return parseSpecifier(d, locale_time, string4, 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" };
var numberRe = /^\s*\d+/;
var percentRe = /^%/;
var requoteRe = /[\\^$*+?|[\]().{}]/g;
function pad(value, fill, width) {
  var sign = value < 0 ? "-" : "", string4 = (sign ? -value : value) + "", length = string4.length;
  return sign + (length < width ? new Array(width - length + 1).join(fill) + string4 : string4);
}
function requote(s2) {
  return s2.replace(requoteRe, "\\$&");
}
function formatRe(names) {
  return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}
function formatLookup(names) {
  return new Map(names.map((name, i) => [name.toLowerCase(), i]));
}
function parseWeekdayNumberSunday(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 1));
  return n2 ? (d.w = +n2[0], i + n2[0].length) : -1;
}
function parseWeekdayNumberMonday(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 1));
  return n2 ? (d.u = +n2[0], i + n2[0].length) : -1;
}
function parseWeekNumberSunday(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 2));
  return n2 ? (d.U = +n2[0], i + n2[0].length) : -1;
}
function parseWeekNumberISO(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 2));
  return n2 ? (d.V = +n2[0], i + n2[0].length) : -1;
}
function parseWeekNumberMonday(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 2));
  return n2 ? (d.W = +n2[0], i + n2[0].length) : -1;
}
function parseFullYear(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 4));
  return n2 ? (d.y = +n2[0], i + n2[0].length) : -1;
}
function parseYear(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 2));
  return n2 ? (d.y = +n2[0] + (+n2[0] > 68 ? 1900 : 2e3), i + n2[0].length) : -1;
}
function parseZone(d, string4, i) {
  var n2 = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string4.slice(i, i + 6));
  return n2 ? (d.Z = n2[1] ? 0 : -(n2[2] + (n2[3] || "00")), i + n2[0].length) : -1;
}
function parseQuarter(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 1));
  return n2 ? (d.q = n2[0] * 3 - 3, i + n2[0].length) : -1;
}
function parseMonthNumber(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 2));
  return n2 ? (d.m = n2[0] - 1, i + n2[0].length) : -1;
}
function parseDayOfMonth(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 2));
  return n2 ? (d.d = +n2[0], i + n2[0].length) : -1;
}
function parseDayOfYear(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 3));
  return n2 ? (d.m = 0, d.d = +n2[0], i + n2[0].length) : -1;
}
function parseHour24(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 2));
  return n2 ? (d.H = +n2[0], i + n2[0].length) : -1;
}
function parseMinutes(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 2));
  return n2 ? (d.M = +n2[0], i + n2[0].length) : -1;
}
function parseSeconds(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 2));
  return n2 ? (d.S = +n2[0], i + n2[0].length) : -1;
}
function parseMilliseconds(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 3));
  return n2 ? (d.L = +n2[0], i + n2[0].length) : -1;
}
function parseMicroseconds(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i, i + 6));
  return n2 ? (d.L = Math.floor(n2[0] / 1e3), i + n2[0].length) : -1;
}
function parseLiteralPercent(d, string4, i) {
  var n2 = percentRe.exec(string4.slice(i, i + 1));
  return n2 ? i + n2[0].length : -1;
}
function parseUnixTimestamp(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i));
  return n2 ? (d.Q = +n2[0], i + n2[0].length) : -1;
}
function parseUnixTimestampSeconds(d, string4, i) {
  var n2 = numberRe.exec(string4.slice(i));
  return n2 ? (d.s = +n2[0], i + n2[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 + timeDay.count(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(timeSunday.count(timeYear(d) - 1, d), p, 2);
}
function dISO(d) {
  var day = d.getDay();
  return day >= 4 || day === 0 ? timeThursday(d) : timeThursday.ceil(d);
}
function formatWeekNumberISO(d, p) {
  d = dISO(d);
  return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2);
}
function formatWeekdayNumberSunday(d) {
  return d.getDay();
}
function formatWeekNumberMonday(d, p) {
  return pad(timeMonday.count(timeYear(d) - 1, d), p, 2);
}
function formatYear(d, p) {
  return pad(d.getFullYear() % 100, p, 2);
}
function formatYearISO(d, p) {
  d = dISO(d);
  return pad(d.getFullYear() % 100, p, 2);
}
function formatFullYear(d, p) {
  return pad(d.getFullYear() % 1e4, p, 4);
}
function formatFullYearISO(d, p) {
  var day = d.getDay();
  d = day >= 4 || day === 0 ? timeThursday(d) : timeThursday.ceil(d);
  return pad(d.getFullYear() % 1e4, p, 4);
}
function formatZone(d) {
  var z2 = d.getTimezoneOffset();
  return (z2 > 0 ? "-" : (z2 *= -1, "+")) + pad(z2 / 60 | 0, "0", 2) + pad(z2 % 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 + utcDay.count(utcYear(d), d), p, 3);
}
function formatUTCMilliseconds(d, p) {
  return pad(d.getUTCMilliseconds(), p, 3);
}
function formatUTCMicroseconds(d, p) {
  return formatUTCMilliseconds(d, p) + "000";
}
function formatUTCMonthNumber(d, p) {
  return pad(d.getUTCMonth() + 1, p, 2);
}
function formatUTCMinutes(d, p) {
  return pad(d.getUTCMinutes(), p, 2);
}
function formatUTCSeconds(d, p) {
  return pad(d.getUTCSeconds(), p, 2);
}
function formatUTCWeekdayNumberMonday(d) {
  var dow = d.getUTCDay();
  return dow === 0 ? 7 : dow;
}
function formatUTCWeekNumberSunday(d, p) {
  return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);
}
function UTCdISO(d) {
  var day = d.getUTCDay();
  return day >= 4 || day === 0 ? utcThursday(d) : utcThursday.ceil(d);
}
function formatUTCWeekNumberISO(d, p) {
  d = UTCdISO(d);
  return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2);
}
function formatUTCWeekdayNumberSunday(d) {
  return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
  return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);
}
function formatUTCYear(d, p) {
  return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCYearISO(d, p) {
  d = UTCdISO(d);
  return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCFullYear(d, p) {
  return pad(d.getUTCFullYear() % 1e4, p, 4);
}
function formatUTCFullYearISO(d, p) {
  var day = d.getUTCDay();
  d = day >= 4 || day === 0 ? utcThursday(d) : utcThursday.ceil(d);
  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);
}

// node_modules/d3-time-format/src/defaultLocale.js
var locale2;
var timeFormat;
var timeParse;
var utcFormat;
var utcParse;
defaultLocale3({
  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 defaultLocale3(definition) {
  locale2 = formatLocale(definition);
  timeFormat = locale2.format;
  timeParse = locale2.parse;
  utcFormat = locale2.utcFormat;
  utcParse = locale2.utcParse;
  return locale2;
}

// node_modules/d3-scale/src/time.js
function date(t) {
  return new Date(t);
}
function number3(t) {
  return t instanceof Date ? +t : +/* @__PURE__ */ new Date(+t);
}
function calendar(ticks2, tickInterval, year, month, week, day, hour, minute, second2, format2) {
  var scale = continuous(), invert = scale.invert, domain2 = scale.domain;
  var formatMillisecond = format2(".%L"), formatSecond = format2(":%S"), formatMinute = format2("%I:%M"), formatHour = format2("%I %p"), formatDay = format2("%a %d"), formatWeek = format2("%b %d"), formatMonth = format2("%B"), formatYear3 = format2("%Y");
  function tickFormat2(date6) {
    return (second2(date6) < date6 ? formatMillisecond : minute(date6) < date6 ? formatSecond : hour(date6) < date6 ? formatMinute : day(date6) < date6 ? formatHour : month(date6) < date6 ? week(date6) < date6 ? formatDay : formatWeek : year(date6) < date6 ? formatMonth : formatYear3)(date6);
  }
  scale.invert = function(y2) {
    return new Date(invert(y2));
  };
  scale.domain = function(_) {
    return arguments.length ? domain2(Array.from(_, number3)) : domain2().map(date);
  };
  scale.ticks = function(interval2) {
    var d = domain2();
    return ticks2(d[0], d[d.length - 1], interval2 == null ? 10 : interval2);
  };
  scale.tickFormat = function(count, specifier) {
    return specifier == null ? tickFormat2 : format2(specifier);
  };
  scale.nice = function(interval2) {
    var d = domain2();
    if (!interval2 || typeof interval2.range !== "function") interval2 = tickInterval(d[0], d[d.length - 1], interval2 == null ? 10 : interval2);
    return interval2 ? domain2(nice(d, interval2)) : scale;
  };
  scale.copy = function() {
    return copy(scale, calendar(ticks2, tickInterval, year, month, week, day, hour, minute, second2, format2));
  };
  return scale;
}

// node_modules/d3-scale/src/utcTime.js
function utcTime() {
  return initRange.apply(calendar(utcTicks, utcTickInterval, utcYear, utcMonth, utcSunday, utcDay, utcHour, utcMinute, second, utcFormat).domain([Date.UTC(2e3, 0, 1), Date.UTC(2e3, 0, 2)]), arguments);
}

// node_modules/d3-selection/src/namespaces.js
var xhtml = "http://www.w3.org/1999/xhtml";
var namespaces_default = {
  svg: "http://www.w3.org/2000/svg",
  xhtml,
  xlink: "http://www.w3.org/1999/xlink",
  xml: "http://www.w3.org/XML/1998/namespace",
  xmlns: "http://www.w3.org/2000/xmlns/"
};

// node_modules/d3-selection/src/namespace.js
function namespace_default(name) {
  var prefix = name += "", i = prefix.indexOf(":");
  if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
  return namespaces_default.hasOwnProperty(prefix) ? { space: namespaces_default[prefix], local: name } : name;
}

// node_modules/d3-selection/src/creator.js
function creatorInherit(name) {
  return function() {
    var document2 = this.ownerDocument, uri = this.namespaceURI;
    return uri === xhtml && document2.documentElement.namespaceURI === xhtml ? document2.createElement(name) : document2.createElementNS(uri, name);
  };
}
function creatorFixed(fullname) {
  return function() {
    return this.ownerDocument.createElementNS(fullname.space, fullname.local);
  };
}
function creator_default(name) {
  var fullname = namespace_default(name);
  return (fullname.local ? creatorFixed : creatorInherit)(fullname);
}

// node_modules/d3-selection/src/selector.js
function none() {
}
function selector_default(selector) {
  return selector == null ? none : function() {
    return this.querySelector(selector);
  };
}

// node_modules/d3-selection/src/selection/select.js
function select_default(select) {
  if (typeof select !== "function") select = selector_default(select);
  for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group = groups[j], n2 = group.length, subgroup = subgroups[j] = new Array(n2), node, subnode, i = 0; i < n2; ++i) {
      if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {
        if ("__data__" in node) subnode.__data__ = node.__data__;
        subgroup[i] = subnode;
      }
    }
  }
  return new Selection(subgroups, this._parents);
}

// node_modules/d3-selection/src/array.js
function array(x2) {
  return x2 == null ? [] : Array.isArray(x2) ? x2 : Array.from(x2);
}

// node_modules/d3-selection/src/selectorAll.js
function empty() {
  return [];
}
function selectorAll_default(selector) {
  return selector == null ? empty : function() {
    return this.querySelectorAll(selector);
  };
}

// node_modules/d3-selection/src/selection/selectAll.js
function arrayAll(select) {
  return function() {
    return array(select.apply(this, arguments));
  };
}
function selectAll_default(select) {
  if (typeof select === "function") select = arrayAll(select);
  else select = selectorAll_default(select);
  for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
    for (var group = groups[j], n2 = group.length, node, i = 0; i < n2; ++i) {
      if (node = group[i]) {
        subgroups.push(select.call(node, node.__data__, i, group));
        parents.push(node);
      }
    }
  }
  return new Selection(subgroups, parents);
}

// node_modules/d3-selection/src/matcher.js
function matcher_default(selector) {
  return function() {
    return this.matches(selector);
  };
}
function childMatcher(selector) {
  return function(node) {
    return node.matches(selector);
  };
}

// node_modules/d3-selection/src/selection/selectChild.js
var find = Array.prototype.find;
function childFind(match2) {
  return function() {
    return find.call(this.children, match2);
  };
}
function childFirst() {
  return this.firstElementChild;
}
function selectChild_default(match2) {
  return this.select(match2 == null ? childFirst : childFind(typeof match2 === "function" ? match2 : childMatcher(match2)));
}

// node_modules/d3-selection/src/selection/selectChildren.js
var filter = Array.prototype.filter;
function children() {
  return Array.from(this.children);
}
function childrenFilter(match2) {
  return function() {
    return filter.call(this.children, match2);
  };
}
function selectChildren_default(match2) {
  return this.selectAll(match2 == null ? children : childrenFilter(typeof match2 === "function" ? match2 : childMatcher(match2)));
}

// node_modules/d3-selection/src/selection/filter.js
function filter_default(match2) {
  if (typeof match2 !== "function") match2 = matcher_default(match2);
  for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group = groups[j], n2 = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n2; ++i) {
      if ((node = group[i]) && match2.call(node, node.__data__, i, group)) {
        subgroup.push(node);
      }
    }
  }
  return new Selection(subgroups, this._parents);
}

// node_modules/d3-selection/src/selection/sparse.js
function sparse_default(update) {
  return new Array(update.length);
}

// node_modules/d3-selection/src/selection/enter.js
function enter_default() {
  return new Selection(this._enter || this._groups.map(sparse_default), this._parents);
}
function EnterNode(parent, datum2) {
  this.ownerDocument = parent.ownerDocument;
  this.namespaceURI = parent.namespaceURI;
  this._next = null;
  this._parent = parent;
  this.__data__ = datum2;
}
EnterNode.prototype = {
  constructor: EnterNode,
  appendChild: function(child) {
    return this._parent.insertBefore(child, this._next);
  },
  insertBefore: function(child, next) {
    return this._parent.insertBefore(child, next);
  },
  querySelector: function(selector) {
    return this._parent.querySelector(selector);
  },
  querySelectorAll: function(selector) {
    return this._parent.querySelectorAll(selector);
  }
};

// node_modules/d3-selection/src/constant.js
function constant_default2(x2) {
  return function() {
    return x2;
  };
}

// node_modules/d3-selection/src/selection/data.js
function bindIndex(parent, group, enter, update, exit, data) {
  var i = 0, node, groupLength = group.length, dataLength = data.length;
  for (; i < dataLength; ++i) {
    if (node = group[i]) {
      node.__data__ = data[i];
      update[i] = node;
    } else {
      enter[i] = new EnterNode(parent, data[i]);
    }
  }
  for (; i < groupLength; ++i) {
    if (node = group[i]) {
      exit[i] = node;
    }
  }
}
function bindKey(parent, group, enter, update, exit, data, key) {
  var i, node, nodeByKeyValue = /* @__PURE__ */ new Map(), groupLength = group.length, dataLength = data.length, keyValues = new Array(groupLength), keyValue;
  for (i = 0; i < groupLength; ++i) {
    if (node = group[i]) {
      keyValues[i] = keyValue = key.call(node, node.__data__, i, group) + "";
      if (nodeByKeyValue.has(keyValue)) {
        exit[i] = node;
      } else {
        nodeByKeyValue.set(keyValue, node);
      }
    }
  }
  for (i = 0; i < dataLength; ++i) {
    keyValue = key.call(parent, data[i], i, data) + "";
    if (node = nodeByKeyValue.get(keyValue)) {
      update[i] = node;
      node.__data__ = data[i];
      nodeByKeyValue.delete(keyValue);
    } else {
      enter[i] = new EnterNode(parent, data[i]);
    }
  }
  for (i = 0; i < groupLength; ++i) {
    if ((node = group[i]) && nodeByKeyValue.get(keyValues[i]) === node) {
      exit[i] = node;
    }
  }
}
function datum(node) {
  return node.__data__;
}
function data_default(value, key) {
  if (!arguments.length) return Array.from(this, datum);
  var bind = key ? bindKey : bindIndex, parents = this._parents, groups = this._groups;
  if (typeof value !== "function") value = constant_default2(value);
  for (var m = groups.length, update = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) {
    var parent = parents[j], group = groups[j], groupLength = group.length, data = arraylike(value.call(parent, parent && parent.__data__, j, parents)), dataLength = data.length, enterGroup = enter[j] = new Array(dataLength), updateGroup = update[j] = new Array(dataLength), exitGroup = exit[j] = new Array(groupLength);
    bind(parent, group, enterGroup, updateGroup, exitGroup, data, key);
    for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
      if (previous = enterGroup[i0]) {
        if (i0 >= i1) i1 = i0 + 1;
        while (!(next = updateGroup[i1]) && ++i1 < dataLength) ;
        previous._next = next || null;
      }
    }
  }
  update = new Selection(update, parents);
  update._enter = enter;
  update._exit = exit;
  return update;
}
function arraylike(data) {
  return typeof data === "object" && "length" in data ? data : Array.from(data);
}

// node_modules/d3-selection/src/selection/exit.js
function exit_default() {
  return new Selection(this._exit || this._groups.map(sparse_default), this._parents);
}

// node_modules/d3-selection/src/selection/join.js
function join_default(onenter, onupdate, onexit) {
  var enter = this.enter(), update = this, exit = this.exit();
  if (typeof onenter === "function") {
    enter = onenter(enter);
    if (enter) enter = enter.selection();
  } else {
    enter = enter.append(onenter + "");
  }
  if (onupdate != null) {
    update = onupdate(update);
    if (update) update = update.selection();
  }
  if (onexit == null) exit.remove();
  else onexit(exit);
  return enter && update ? enter.merge(update).order() : update;
}

// node_modules/d3-selection/src/selection/merge.js
function merge_default(context) {
  var selection2 = context.selection ? context.selection() : context;
  for (var groups0 = this._groups, groups1 = selection2._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
    for (var group0 = groups0[j], group1 = groups1[j], n2 = group0.length, merge4 = merges[j] = new Array(n2), node, i = 0; i < n2; ++i) {
      if (node = group0[i] || group1[i]) {
        merge4[i] = node;
      }
    }
  }
  for (; j < m0; ++j) {
    merges[j] = groups0[j];
  }
  return new Selection(merges, this._parents);
}

// node_modules/d3-selection/src/selection/order.js
function order_default() {
  for (var groups = this._groups, j = -1, m = groups.length; ++j < m; ) {
    for (var group = groups[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
      if (node = group[i]) {
        if (next && node.compareDocumentPosition(next) ^ 4) next.parentNode.insertBefore(node, next);
        next = node;
      }
    }
  }
  return this;
}

// node_modules/d3-selection/src/selection/sort.js
function sort_default(compare) {
  if (!compare) compare = ascending2;
  function compareNode(a, b) {
    return a && b ? compare(a.__data__, b.__data__) : !a - !b;
  }
  for (var groups = this._groups, m = groups.length, sortgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group = groups[j], n2 = group.length, sortgroup = sortgroups[j] = new Array(n2), node, i = 0; i < n2; ++i) {
      if (node = group[i]) {
        sortgroup[i] = node;
      }
    }
    sortgroup.sort(compareNode);
  }
  return new Selection(sortgroups, this._parents).order();
}
function ascending2(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

// node_modules/d3-selection/src/selection/call.js
function call_default() {
  var callback = arguments[0];
  arguments[0] = this;
  callback.apply(null, arguments);
  return this;
}

// node_modules/d3-selection/src/selection/nodes.js
function nodes_default() {
  return Array.from(this);
}

// node_modules/d3-selection/src/selection/node.js
function node_default() {
  for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
    for (var group = groups[j], i = 0, n2 = group.length; i < n2; ++i) {
      var node = group[i];
      if (node) return node;
    }
  }
  return null;
}

// node_modules/d3-selection/src/selection/size.js
function size_default() {
  let size = 0;
  for (const node of this) ++size;
  return size;
}

// node_modules/d3-selection/src/selection/empty.js
function empty_default() {
  return !this.node();
}

// node_modules/d3-selection/src/selection/each.js
function each_default(callback) {
  for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
    for (var group = groups[j], i = 0, n2 = group.length, node; i < n2; ++i) {
      if (node = group[i]) callback.call(node, node.__data__, i, group);
    }
  }
  return this;
}

// node_modules/d3-selection/src/selection/attr.js
function attrRemove(name) {
  return function() {
    this.removeAttribute(name);
  };
}
function attrRemoveNS(fullname) {
  return function() {
    this.removeAttributeNS(fullname.space, fullname.local);
  };
}
function attrConstant(name, value) {
  return function() {
    this.setAttribute(name, value);
  };
}
function attrConstantNS(fullname, value) {
  return function() {
    this.setAttributeNS(fullname.space, fullname.local, value);
  };
}
function attrFunction(name, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.removeAttribute(name);
    else this.setAttribute(name, v);
  };
}
function attrFunctionNS(fullname, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.removeAttributeNS(fullname.space, fullname.local);
    else this.setAttributeNS(fullname.space, fullname.local, v);
  };
}
function attr_default(name, value) {
  var fullname = namespace_default(name);
  if (arguments.length < 2) {
    var node = this.node();
    return fullname.local ? node.getAttributeNS(fullname.space, fullname.local) : node.getAttribute(fullname);
  }
  return this.each((value == null ? fullname.local ? attrRemoveNS : attrRemove : typeof value === "function" ? fullname.local ? attrFunctionNS : attrFunction : fullname.local ? attrConstantNS : attrConstant)(fullname, value));
}

// node_modules/d3-selection/src/window.js
function window_default(node) {
  return node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView;
}

// node_modules/d3-selection/src/selection/style.js
function styleRemove(name) {
  return function() {
    this.style.removeProperty(name);
  };
}
function styleConstant(name, value, priority) {
  return function() {
    this.style.setProperty(name, value, priority);
  };
}
function styleFunction(name, value, priority) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.style.removeProperty(name);
    else this.style.setProperty(name, v, priority);
  };
}
function style_default(name, value, priority) {
  return arguments.length > 1 ? this.each((value == null ? styleRemove : typeof value === "function" ? styleFunction : styleConstant)(name, value, priority == null ? "" : priority)) : styleValue(this.node(), name);
}
function styleValue(node, name) {
  return node.style.getPropertyValue(name) || window_default(node).getComputedStyle(node, null).getPropertyValue(name);
}

// node_modules/d3-selection/src/selection/property.js
function propertyRemove(name) {
  return function() {
    delete this[name];
  };
}
function propertyConstant(name, value) {
  return function() {
    this[name] = value;
  };
}
function propertyFunction(name, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) delete this[name];
    else this[name] = v;
  };
}
function property_default(name, value) {
  return arguments.length > 1 ? this.each((value == null ? propertyRemove : typeof value === "function" ? propertyFunction : propertyConstant)(name, value)) : this.node()[name];
}

// node_modules/d3-selection/src/selection/classed.js
function classArray(string4) {
  return string4.trim().split(/^|\s+/);
}
function classList(node) {
  return node.classList || new ClassList(node);
}
function ClassList(node) {
  this._node = node;
  this._names = classArray(node.getAttribute("class") || "");
}
ClassList.prototype = {
  add: function(name) {
    var i = this._names.indexOf(name);
    if (i < 0) {
      this._names.push(name);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  remove: function(name) {
    var i = this._names.indexOf(name);
    if (i >= 0) {
      this._names.splice(i, 1);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  contains: function(name) {
    return this._names.indexOf(name) >= 0;
  }
};
function classedAdd(node, names) {
  var list = classList(node), i = -1, n2 = names.length;
  while (++i < n2) list.add(names[i]);
}
function classedRemove(node, names) {
  var list = classList(node), i = -1, n2 = names.length;
  while (++i < n2) list.remove(names[i]);
}
function classedTrue(names) {
  return function() {
    classedAdd(this, names);
  };
}
function classedFalse(names) {
  return function() {
    classedRemove(this, names);
  };
}
function classedFunction(names, value) {
  return function() {
    (value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
  };
}
function classed_default(name, value) {
  var names = classArray(name + "");
  if (arguments.length < 2) {
    var list = classList(this.node()), i = -1, n2 = names.length;
    while (++i < n2) if (!list.contains(names[i])) return false;
    return true;
  }
  return this.each((typeof value === "function" ? classedFunction : value ? classedTrue : classedFalse)(names, value));
}

// node_modules/d3-selection/src/selection/text.js
function textRemove() {
  this.textContent = "";
}
function textConstant(value) {
  return function() {
    this.textContent = value;
  };
}
function textFunction(value) {
  return function() {
    var v = value.apply(this, arguments);
    this.textContent = v == null ? "" : v;
  };
}
function text_default(value) {
  return arguments.length ? this.each(value == null ? textRemove : (typeof value === "function" ? textFunction : textConstant)(value)) : this.node().textContent;
}

// node_modules/d3-selection/src/selection/html.js
function htmlRemove() {
  this.innerHTML = "";
}
function htmlConstant(value) {
  return function() {
    this.innerHTML = value;
  };
}
function htmlFunction(value) {
  return function() {
    var v = value.apply(this, arguments);
    this.innerHTML = v == null ? "" : v;
  };
}
function html_default(value) {
  return arguments.length ? this.each(value == null ? htmlRemove : (typeof value === "function" ? htmlFunction : htmlConstant)(value)) : this.node().innerHTML;
}

// node_modules/d3-selection/src/selection/raise.js
function raise() {
  if (this.nextSibling) this.parentNode.appendChild(this);
}
function raise_default() {
  return this.each(raise);
}

// node_modules/d3-selection/src/selection/lower.js
function lower() {
  if (this.previousSibling) this.parentNode.insertBefore(this, this.parentNode.firstChild);
}
function lower_default() {
  return this.each(lower);
}

// node_modules/d3-selection/src/selection/append.js
function append_default(name) {
  var create2 = typeof name === "function" ? name : creator_default(name);
  return this.select(function() {
    return this.appendChild(create2.apply(this, arguments));
  });
}

// node_modules/d3-selection/src/selection/insert.js
function constantNull() {
  return null;
}
function insert_default(name, before) {
  var create2 = typeof name === "function" ? name : creator_default(name), select = before == null ? constantNull : typeof before === "function" ? before : selector_default(before);
  return this.select(function() {
    return this.insertBefore(create2.apply(this, arguments), select.apply(this, arguments) || null);
  });
}

// node_modules/d3-selection/src/selection/remove.js
function remove() {
  var parent = this.parentNode;
  if (parent) parent.removeChild(this);
}
function remove_default() {
  return this.each(remove);
}

// node_modules/d3-selection/src/selection/clone.js
function selection_cloneShallow() {
  var clone3 = this.cloneNode(false), parent = this.parentNode;
  return parent ? parent.insertBefore(clone3, this.nextSibling) : clone3;
}
function selection_cloneDeep() {
  var clone3 = this.cloneNode(true), parent = this.parentNode;
  return parent ? parent.insertBefore(clone3, this.nextSibling) : clone3;
}
function clone_default(deep) {
  return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
}

// node_modules/d3-selection/src/selection/datum.js
function datum_default(value) {
  return arguments.length ? this.property("__data__", value) : this.node().__data__;
}

// node_modules/d3-selection/src/selection/on.js
function contextListener(listener) {
  return function(event) {
    listener.call(this, event, this.__data__);
  };
}
function parseTypenames(typenames) {
  return typenames.trim().split(/^|\s+/).map(function(t) {
    var name = "", i = t.indexOf(".");
    if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
    return { type: t, name };
  });
}
function onRemove(typename) {
  return function() {
    var on = this.__on;
    if (!on) return;
    for (var j = 0, i = -1, m = on.length, o; j < m; ++j) {
      if (o = on[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.options);
      } else {
        on[++i] = o;
      }
    }
    if (++i) on.length = i;
    else delete this.__on;
  };
}
function onAdd(typename, value, options) {
  return function() {
    var on = this.__on, o, listener = contextListener(value);
    if (on) for (var j = 0, m = on.length; j < m; ++j) {
      if ((o = on[j]).type === typename.type && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.options);
        this.addEventListener(o.type, o.listener = listener, o.options = options);
        o.value = value;
        return;
      }
    }
    this.addEventListener(typename.type, listener, options);
    o = { type: typename.type, name: typename.name, value, listener, options };
    if (!on) this.__on = [o];
    else on.push(o);
  };
}
function on_default(typename, value, options) {
  var typenames = parseTypenames(typename + ""), i, n2 = typenames.length, t;
  if (arguments.length < 2) {
    var on = this.node().__on;
    if (on) for (var j = 0, m = on.length, o; j < m; ++j) {
      for (i = 0, o = on[j]; i < n2; ++i) {
        if ((t = typenames[i]).type === o.type && t.name === o.name) {
          return o.value;
        }
      }
    }
    return;
  }
  on = value ? onAdd : onRemove;
  for (i = 0; i < n2; ++i) this.each(on(typenames[i], value, options));
  return this;
}

// node_modules/d3-selection/src/selection/dispatch.js
function dispatchEvent(node, type, params) {
  var window2 = window_default(node), event = window2.CustomEvent;
  if (typeof event === "function") {
    event = new event(type, params);
  } else {
    event = window2.document.createEvent("Event");
    if (params) event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail;
    else event.initEvent(type, false, false);
  }
  node.dispatchEvent(event);
}
function dispatchConstant(type, params) {
  return function() {
    return dispatchEvent(this, type, params);
  };
}
function dispatchFunction(type, params) {
  return function() {
    return dispatchEvent(this, type, params.apply(this, arguments));
  };
}
function dispatch_default(type, params) {
  return this.each((typeof params === "function" ? dispatchFunction : dispatchConstant)(type, params));
}

// node_modules/d3-selection/src/selection/iterator.js
function* iterator_default() {
  for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
    for (var group = groups[j], i = 0, n2 = group.length, node; i < n2; ++i) {
      if (node = group[i]) yield node;
    }
  }
}

// node_modules/d3-selection/src/selection/index.js
var root = [null];
function Selection(groups, parents) {
  this._groups = groups;
  this._parents = parents;
}
function selection() {
  return new Selection([[document.documentElement]], root);
}
function selection_selection() {
  return this;
}
Selection.prototype = selection.prototype = {
  constructor: Selection,
  select: select_default,
  selectAll: selectAll_default,
  selectChild: selectChild_default,
  selectChildren: selectChildren_default,
  filter: filter_default,
  data: data_default,
  enter: enter_default,
  exit: exit_default,
  join: join_default,
  merge: merge_default,
  selection: selection_selection,
  order: order_default,
  sort: sort_default,
  call: call_default,
  nodes: nodes_default,
  node: node_default,
  size: size_default,
  empty: empty_default,
  each: each_default,
  attr: attr_default,
  style: style_default,
  property: property_default,
  classed: classed_default,
  text: text_default,
  html: html_default,
  raise: raise_default,
  lower: lower_default,
  append: append_default,
  insert: insert_default,
  remove: remove_default,
  clone: clone_default,
  datum: datum_default,
  on: on_default,
  dispatch: dispatch_default,
  [Symbol.iterator]: iterator_default
};
var selection_default = selection;

// node_modules/d3-selection/src/select.js
function select_default2(selector) {
  return typeof selector === "string" ? new Selection([[document.querySelector(selector)]], [document.documentElement]) : new Selection([[selector]], root);
}

// node_modules/d3-dispatch/src/dispatch.js
var noop = { value: () => {
} };
function dispatch() {
  for (var i = 0, n2 = arguments.length, _ = {}, t; i < n2; ++i) {
    if (!(t = arguments[i] + "") || t in _ || /[\s.]/.test(t)) throw new Error("illegal type: " + t);
    _[t] = [];
  }
  return new Dispatch(_);
}
function Dispatch(_) {
  this._ = _;
}
function parseTypenames2(typenames, types) {
  return typenames.trim().split(/^|\s+/).map(function(t) {
    var name = "", i = t.indexOf(".");
    if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
    if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t);
    return { type: t, name };
  });
}
Dispatch.prototype = dispatch.prototype = {
  constructor: Dispatch,
  on: function(typename, callback) {
    var _ = this._, T = parseTypenames2(typename + "", _), t, i = -1, n2 = T.length;
    if (arguments.length < 2) {
      while (++i < n2) 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 < n2) {
      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 copy2 = {}, _ = this._;
    for (var t in _) copy2[t] = _[t].slice();
    return new Dispatch(copy2);
  },
  call: function(type, that) {
    if ((n2 = arguments.length - 2) > 0) for (var args = new Array(n2), i = 0, n2, t; i < n2; ++i) args[i] = arguments[i + 2];
    if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
    for (t = this._[type], i = 0, n2 = t.length; i < n2; ++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, n2 = t.length; i < n2; ++i) t[i].value.apply(that, args);
  }
};
function get(type, name) {
  for (var i = 0, n2 = type.length, c; i < n2; ++i) {
    if ((c = type[i]).name === name) {
      return c.value;
    }
  }
}
function set(type, name, callback) {
  for (var i = 0, n2 = type.length; i < n2; ++i) {
    if (type[i].name === name) {
      type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));
      break;
    }
  }
  if (callback != null) type.push({ name, value: callback });
  return type;
}
var dispatch_default2 = dispatch;

// node_modules/d3-timer/src/timer.js
var frame = 0;
var timeout = 0;
var interval = 0;
var pokeDelay = 1e3;
var taskHead;
var taskTail;
var clockLast = 0;
var clockNow = 0;
var clockSkew = 0;
var clock = typeof performance === "object" && performance.now ? performance : Date;
var setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) {
  setTimeout(f, 17);
};
function now2() {
  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, time3) {
    if (typeof callback !== "function") throw new TypeError("callback is not a function");
    time3 = (time3 == null ? now2() : +time3) + (delay == null ? 0 : +delay);
    if (!this._next && taskTail !== this) {
      if (taskTail) taskTail._next = this;
      else taskHead = this;
      taskTail = this;
    }
    this._call = callback;
    this._time = time3;
    sleep();
  },
  stop: function() {
    if (this._call) {
      this._call = null;
      this._time = Infinity;
      sleep();
    }
  }
};
function timer(callback, delay, time3) {
  var t = new Timer();
  t.restart(callback, delay, time3);
  return t;
}
function timerFlush() {
  now2();
  ++frame;
  var t = taskHead, e;
  while (t) {
    if ((e = clockNow - t._time) >= 0) t._call.call(void 0, 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 now3 = clock.now(), delay = now3 - clockLast;
  if (delay > pokeDelay) clockSkew -= delay, clockLast = now3;
}
function nap() {
  var t02, t12 = taskHead, t2, time3 = Infinity;
  while (t12) {
    if (t12._call) {
      if (time3 > t12._time) time3 = t12._time;
      t02 = t12, t12 = t12._next;
    } else {
      t2 = t12._next, t12._next = null;
      t12 = t02 ? t02._next = t2 : taskHead = t2;
    }
  }
  taskTail = t02;
  sleep(time3);
}
function sleep(time3) {
  if (frame) return;
  if (timeout) timeout = clearTimeout(timeout);
  var delay = time3 - clockNow;
  if (delay > 24) {
    if (time3 < Infinity) timeout = setTimeout(wake, time3 - clock.now() - clockSkew);
    if (interval) interval = clearInterval(interval);
  } else {
    if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay);
    frame = 1, setFrame(wake);
  }
}

// node_modules/d3-timer/src/timeout.js
function timeout_default(callback, delay, time3) {
  var t = new Timer();
  delay = delay == null ? 0 : +delay;
  t.restart((elapsed) => {
    t.stop();
    callback(elapsed + delay);
  }, delay, time3);
  return t;
}

// node_modules/d3-transition/src/transition/schedule.js
var emptyOn = dispatch_default2("start", "end", "cancel", "interrupt");
var emptyTween = [];
var CREATED = 0;
var SCHEDULED = 1;
var STARTING = 2;
var STARTED = 3;
var RUNNING = 4;
var ENDING = 5;
var ENDED = 6;
function schedule_default(node, name, id2, index, group, timing) {
  var schedules = node.__transition;
  if (!schedules) node.__transition = {};
  else if (id2 in schedules) return;
  create(node, id2, {
    name,
    index,
    // For context during callback.
    group,
    // For context during callback.
    on: emptyOn,
    tween: emptyTween,
    time: timing.time,
    delay: timing.delay,
    duration: timing.duration,
    ease: timing.ease,
    timer: null,
    state: CREATED
  });
}
function init(node, id2) {
  var schedule = get2(node, id2);
  if (schedule.state > CREATED) throw new Error("too late; already scheduled");
  return schedule;
}
function set2(node, id2) {
  var schedule = get2(node, id2);
  if (schedule.state > STARTED) throw new Error("too late; already running");
  return schedule;
}
function get2(node, id2) {
  var schedule = node.__transition;
  if (!schedule || !(schedule = schedule[id2])) throw new Error("transition not found");
  return schedule;
}
function create(node, id2, self2) {
  var schedules = node.__transition, tween;
  schedules[id2] = self2;
  self2.timer = timer(schedule, 0, self2.time);
  function schedule(elapsed) {
    self2.state = SCHEDULED;
    self2.timer.restart(start2, self2.delay, self2.time);
    if (self2.delay <= elapsed) start2(elapsed - self2.delay);
  }
  function start2(elapsed) {
    var i, j, n2, o;
    if (self2.state !== SCHEDULED) return stop();
    for (i in schedules) {
      o = schedules[i];
      if (o.name !== self2.name) continue;
      if (o.state === STARTED) return timeout_default(start2);
      if (o.state === RUNNING) {
        o.state = ENDED;
        o.timer.stop();
        o.on.call("interrupt", node, node.__data__, o.index, o.group);
        delete schedules[i];
      } else if (+i < id2) {
        o.state = ENDED;
        o.timer.stop();
        o.on.call("cancel", node, node.__data__, o.index, o.group);
        delete schedules[i];
      }
    }
    timeout_default(function() {
      if (self2.state === STARTED) {
        self2.state = RUNNING;
        self2.timer.restart(tick, self2.delay, self2.time);
        tick(elapsed);
      }
    });
    self2.state = STARTING;
    self2.on.call("start", node, node.__data__, self2.index, self2.group);
    if (self2.state !== STARTING) return;
    self2.state = STARTED;
    tween = new Array(n2 = self2.tween.length);
    for (i = 0, j = -1; i < n2; ++i) {
      if (o = self2.tween[i].value.call(node, node.__data__, self2.index, self2.group)) {
        tween[++j] = o;
      }
    }
    tween.length = j + 1;
  }
  function tick(elapsed) {
    var t = elapsed < self2.duration ? self2.ease.call(null, elapsed / self2.duration) : (self2.timer.restart(stop), self2.state = ENDING, 1), i = -1, n2 = tween.length;
    while (++i < n2) {
      tween[i].call(node, t);
    }
    if (self2.state === ENDING) {
      self2.on.call("end", node, node.__data__, self2.index, self2.group);
      stop();
    }
  }
  function stop() {
    self2.state = ENDED;
    self2.timer.stop();
    delete schedules[id2];
    for (var i in schedules) return;
    delete node.__transition;
  }
}

// node_modules/d3-transition/src/interrupt.js
function interrupt_default(node, name) {
  var schedules = node.__transition, schedule, active, empty2 = true, i;
  if (!schedules) return;
  name = name == null ? null : name + "";
  for (i in schedules) {
    if ((schedule = schedules[i]).name !== name) {
      empty2 = false;
      continue;
    }
    active = schedule.state > STARTING && schedule.state < ENDING;
    schedule.state = ENDED;
    schedule.timer.stop();
    schedule.on.call(active ? "interrupt" : "cancel", node, node.__data__, schedule.index, schedule.group);
    delete schedules[i];
  }
  if (empty2) delete node.__transition;
}

// node_modules/d3-transition/src/selection/interrupt.js
function interrupt_default2(name) {
  return this.each(function() {
    interrupt_default(this, name);
  });
}

// node_modules/d3-transition/src/transition/tween.js
function tweenRemove(id2, name) {
  var tween0, tween1;
  return function() {
    var schedule = set2(this, id2), tween = schedule.tween;
    if (tween !== tween0) {
      tween1 = tween0 = tween;
      for (var i = 0, n2 = tween1.length; i < n2; ++i) {
        if (tween1[i].name === name) {
          tween1 = tween1.slice();
          tween1.splice(i, 1);
          break;
        }
      }
    }
    schedule.tween = tween1;
  };
}
function tweenFunction(id2, name, value) {
  var tween0, tween1;
  if (typeof value !== "function") throw new Error();
  return function() {
    var schedule = set2(this, id2), tween = schedule.tween;
    if (tween !== tween0) {
      tween1 = (tween0 = tween).slice();
      for (var t = { name, value }, i = 0, n2 = tween1.length; i < n2; ++i) {
        if (tween1[i].name === name) {
          tween1[i] = t;
          break;
        }
      }
      if (i === n2) tween1.push(t);
    }
    schedule.tween = tween1;
  };
}
function tween_default(name, value) {
  var id2 = this._id;
  name += "";
  if (arguments.length < 2) {
    var tween = get2(this.node(), id2).tween;
    for (var i = 0, n2 = tween.length, t; i < n2; ++i) {
      if ((t = tween[i]).name === name) {
        return t.value;
      }
    }
    return null;
  }
  return this.each((value == null ? tweenRemove : tweenFunction)(id2, name, value));
}
function tweenValue(transition3, name, value) {
  var id2 = transition3._id;
  transition3.each(function() {
    var schedule = set2(this, id2);
    (schedule.value || (schedule.value = {}))[name] = value.apply(this, arguments);
  });
  return function(node) {
    return get2(node, id2).value[name];
  };
}

// node_modules/d3-transition/src/transition/interpolate.js
function interpolate_default(a, b) {
  var c;
  return (typeof b === "number" ? number_default : b instanceof color ? rgb_default : (c = color(b)) ? (b = c, rgb_default) : string_default)(a, b);
}

// node_modules/d3-transition/src/transition/attr.js
function attrRemove2(name) {
  return function() {
    this.removeAttribute(name);
  };
}
function attrRemoveNS2(fullname) {
  return function() {
    this.removeAttributeNS(fullname.space, fullname.local);
  };
}
function attrConstant2(name, interpolate, value1) {
  var string00, string1 = value1 + "", interpolate0;
  return function() {
    var string0 = this.getAttribute(name);
    return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate(string00 = string0, value1);
  };
}
function attrConstantNS2(fullname, interpolate, value1) {
  var string00, string1 = value1 + "", interpolate0;
  return function() {
    var string0 = this.getAttributeNS(fullname.space, fullname.local);
    return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate(string00 = string0, value1);
  };
}
function attrFunction2(name, interpolate, value) {
  var string00, string10, interpolate0;
  return function() {
    var string0, value1 = value(this), string1;
    if (value1 == null) return void this.removeAttribute(name);
    string0 = this.getAttribute(name);
    string1 = value1 + "";
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));
  };
}
function attrFunctionNS2(fullname, interpolate, value) {
  var string00, string10, interpolate0;
  return function() {
    var string0, value1 = value(this), string1;
    if (value1 == null) return void this.removeAttributeNS(fullname.space, fullname.local);
    string0 = this.getAttributeNS(fullname.space, fullname.local);
    string1 = value1 + "";
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));
  };
}
function attr_default2(name, value) {
  var fullname = namespace_default(name), i = fullname === "transform" ? interpolateTransformSvg : interpolate_default;
  return this.attrTween(name, typeof value === "function" ? (fullname.local ? attrFunctionNS2 : attrFunction2)(fullname, i, tweenValue(this, "attr." + name, value)) : value == null ? (fullname.local ? attrRemoveNS2 : attrRemove2)(fullname) : (fullname.local ? attrConstantNS2 : attrConstant2)(fullname, i, value));
}

// node_modules/d3-transition/src/transition/attrTween.js
function attrInterpolate(name, i) {
  return function(t) {
    this.setAttribute(name, i.call(this, t));
  };
}
function attrInterpolateNS(fullname, i) {
  return function(t) {
    this.setAttributeNS(fullname.space, fullname.local, i.call(this, t));
  };
}
function attrTweenNS(fullname, value) {
  var t02, i0;
  function tween() {
    var i = value.apply(this, arguments);
    if (i !== i0) t02 = (i0 = i) && attrInterpolateNS(fullname, i);
    return t02;
  }
  tween._value = value;
  return tween;
}
function attrTween(name, value) {
  var t02, i0;
  function tween() {
    var i = value.apply(this, arguments);
    if (i !== i0) t02 = (i0 = i) && attrInterpolate(name, i);
    return t02;
  }
  tween._value = value;
  return tween;
}
function attrTween_default(name, value) {
  var key = "attr." + name;
  if (arguments.length < 2) return (key = this.tween(key)) && key._value;
  if (value == null) return this.tween(key, null);
  if (typeof value !== "function") throw new Error();
  var fullname = namespace_default(name);
  return this.tween(key, (fullname.local ? attrTweenNS : attrTween)(fullname, value));
}

// node_modules/d3-transition/src/transition/delay.js
function delayFunction(id2, value) {
  return function() {
    init(this, id2).delay = +value.apply(this, arguments);
  };
}
function delayConstant(id2, value) {
  return value = +value, function() {
    init(this, id2).delay = value;
  };
}
function delay_default(value) {
  var id2 = this._id;
  return arguments.length ? this.each((typeof value === "function" ? delayFunction : delayConstant)(id2, value)) : get2(this.node(), id2).delay;
}

// node_modules/d3-transition/src/transition/duration.js
function durationFunction(id2, value) {
  return function() {
    set2(this, id2).duration = +value.apply(this, arguments);
  };
}
function durationConstant(id2, value) {
  return value = +value, function() {
    set2(this, id2).duration = value;
  };
}
function duration_default(value) {
  var id2 = this._id;
  return arguments.length ? this.each((typeof value === "function" ? durationFunction : durationConstant)(id2, value)) : get2(this.node(), id2).duration;
}

// node_modules/d3-transition/src/transition/ease.js
function easeConstant(id2, value) {
  if (typeof value !== "function") throw new Error();
  return function() {
    set2(this, id2).ease = value;
  };
}
function ease_default(value) {
  var id2 = this._id;
  return arguments.length ? this.each(easeConstant(id2, value)) : get2(this.node(), id2).ease;
}

// node_modules/d3-transition/src/transition/easeVarying.js
function easeVarying(id2, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (typeof v !== "function") throw new Error();
    set2(this, id2).ease = v;
  };
}
function easeVarying_default(value) {
  if (typeof value !== "function") throw new Error();
  return this.each(easeVarying(this._id, value));
}

// node_modules/d3-transition/src/transition/filter.js
function filter_default2(match2) {
  if (typeof match2 !== "function") match2 = matcher_default(match2);
  for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group = groups[j], n2 = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n2; ++i) {
      if ((node = group[i]) && match2.call(node, node.__data__, i, group)) {
        subgroup.push(node);
      }
    }
  }
  return new Transition(subgroups, this._parents, this._name, this._id);
}

// node_modules/d3-transition/src/transition/merge.js
function merge_default2(transition3) {
  if (transition3._id !== this._id) throw new Error();
  for (var groups0 = this._groups, groups1 = transition3._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
    for (var group0 = groups0[j], group1 = groups1[j], n2 = group0.length, merge4 = merges[j] = new Array(n2), node, i = 0; i < n2; ++i) {
      if (node = group0[i] || group1[i]) {
        merge4[i] = node;
      }
    }
  }
  for (; j < m0; ++j) {
    merges[j] = groups0[j];
  }
  return new Transition(merges, this._parents, this._name, this._id);
}

// node_modules/d3-transition/src/transition/on.js
function start(name) {
  return (name + "").trim().split(/^|\s+/).every(function(t) {
    var i = t.indexOf(".");
    if (i >= 0) t = t.slice(0, i);
    return !t || t === "start";
  });
}
function onFunction(id2, name, listener) {
  var on0, on1, sit = start(name) ? init : set2;
  return function() {
    var schedule = sit(this, id2), on = schedule.on;
    if (on !== on0) (on1 = (on0 = on).copy()).on(name, listener);
    schedule.on = on1;
  };
}
function on_default2(name, listener) {
  var id2 = this._id;
  return arguments.length < 2 ? get2(this.node(), id2).on.on(name) : this.each(onFunction(id2, name, listener));
}

// node_modules/d3-transition/src/transition/remove.js
function removeFunction(id2) {
  return function() {
    var parent = this.parentNode;
    for (var i in this.__transition) if (+i !== id2) return;
    if (parent) parent.removeChild(this);
  };
}
function remove_default2() {
  return this.on("end.remove", removeFunction(this._id));
}

// node_modules/d3-transition/src/transition/select.js
function select_default3(select) {
  var name = this._name, id2 = this._id;
  if (typeof select !== "function") select = selector_default(select);
  for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group = groups[j], n2 = group.length, subgroup = subgroups[j] = new Array(n2), node, subnode, i = 0; i < n2; ++i) {
      if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {
        if ("__data__" in node) subnode.__data__ = node.__data__;
        subgroup[i] = subnode;
        schedule_default(subgroup[i], name, id2, i, subgroup, get2(node, id2));
      }
    }
  }
  return new Transition(subgroups, this._parents, name, id2);
}

// node_modules/d3-transition/src/transition/selectAll.js
function selectAll_default2(select) {
  var name = this._name, id2 = this._id;
  if (typeof select !== "function") select = selectorAll_default(select);
  for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
    for (var group = groups[j], n2 = group.length, node, i = 0; i < n2; ++i) {
      if (node = group[i]) {
        for (var children2 = select.call(node, node.__data__, i, group), child, inherit2 = get2(node, id2), k = 0, l2 = children2.length; k < l2; ++k) {
          if (child = children2[k]) {
            schedule_default(child, name, id2, k, children2, inherit2);
          }
        }
        subgroups.push(children2);
        parents.push(node);
      }
    }
  }
  return new Transition(subgroups, parents, name, id2);
}

// node_modules/d3-transition/src/transition/selection.js
var Selection2 = selection_default.prototype.constructor;
function selection_default2() {
  return new Selection2(this._groups, this._parents);
}

// node_modules/d3-transition/src/transition/style.js
function styleNull(name, interpolate) {
  var string00, string10, interpolate0;
  return function() {
    var string0 = styleValue(this, name), string1 = (this.style.removeProperty(name), styleValue(this, name));
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : interpolate0 = interpolate(string00 = string0, string10 = string1);
  };
}
function styleRemove2(name) {
  return function() {
    this.style.removeProperty(name);
  };
}
function styleConstant2(name, interpolate, value1) {
  var string00, string1 = value1 + "", interpolate0;
  return function() {
    var string0 = styleValue(this, name);
    return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate(string00 = string0, value1);
  };
}
function styleFunction2(name, interpolate, value) {
  var string00, string10, interpolate0;
  return function() {
    var string0 = styleValue(this, name), value1 = value(this), string1 = value1 + "";
    if (value1 == null) string1 = value1 = (this.style.removeProperty(name), styleValue(this, name));
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));
  };
}
function styleMaybeRemove(id2, name) {
  var on0, on1, listener0, key = "style." + name, event = "end." + key, remove2;
  return function() {
    var schedule = set2(this, id2), on = schedule.on, listener = schedule.value[key] == null ? remove2 || (remove2 = styleRemove2(name)) : void 0;
    if (on !== on0 || listener0 !== listener) (on1 = (on0 = on).copy()).on(event, listener0 = listener);
    schedule.on = on1;
  };
}
function style_default2(name, value, priority) {
  var i = (name += "") === "transform" ? interpolateTransformCss : interpolate_default;
  return value == null ? this.styleTween(name, styleNull(name, i)).on("end.style." + name, styleRemove2(name)) : typeof value === "function" ? this.styleTween(name, styleFunction2(name, i, tweenValue(this, "style." + name, value))).each(styleMaybeRemove(this._id, name)) : this.styleTween(name, styleConstant2(name, i, value), priority).on("end.style." + name, null);
}

// node_modules/d3-transition/src/transition/styleTween.js
function styleInterpolate(name, i, priority) {
  return function(t) {
    this.style.setProperty(name, i.call(this, t), priority);
  };
}
function styleTween(name, value, priority) {
  var t, i0;
  function tween() {
    var i = value.apply(this, arguments);
    if (i !== i0) t = (i0 = i) && styleInterpolate(name, i, priority);
    return t;
  }
  tween._value = value;
  return tween;
}
function styleTween_default(name, value, priority) {
  var key = "style." + (name += "");
  if (arguments.length < 2) return (key = this.tween(key)) && key._value;
  if (value == null) return this.tween(key, null);
  if (typeof value !== "function") throw new Error();
  return this.tween(key, styleTween(name, value, priority == null ? "" : priority));
}

// node_modules/d3-transition/src/transition/text.js
function textConstant2(value) {
  return function() {
    this.textContent = value;
  };
}
function textFunction2(value) {
  return function() {
    var value1 = value(this);
    this.textContent = value1 == null ? "" : value1;
  };
}
function text_default2(value) {
  return this.tween("text", typeof value === "function" ? textFunction2(tweenValue(this, "text", value)) : textConstant2(value == null ? "" : value + ""));
}

// node_modules/d3-transition/src/transition/textTween.js
function textInterpolate(i) {
  return function(t) {
    this.textContent = i.call(this, t);
  };
}
function textTween(value) {
  var t02, i0;
  function tween() {
    var i = value.apply(this, arguments);
    if (i !== i0) t02 = (i0 = i) && textInterpolate(i);
    return t02;
  }
  tween._value = value;
  return tween;
}
function textTween_default(value) {
  var key = "text";
  if (arguments.length < 1) return (key = this.tween(key)) && key._value;
  if (value == null) return this.tween(key, null);
  if (typeof value !== "function") throw new Error();
  return this.tween(key, textTween(value));
}

// node_modules/d3-transition/src/transition/transition.js
function transition_default() {
  var name = this._name, id0 = this._id, id1 = newId();
  for (var groups = this._groups, m = groups.length, j = 0; j < m; ++j) {
    for (var group = groups[j], n2 = group.length, node, i = 0; i < n2; ++i) {
      if (node = group[i]) {
        var inherit2 = get2(node, id0);
        schedule_default(node, name, id1, i, group, {
          time: inherit2.time + inherit2.delay + inherit2.duration,
          delay: 0,
          duration: inherit2.duration,
          ease: inherit2.ease
        });
      }
    }
  }
  return new Transition(groups, this._parents, name, id1);
}

// node_modules/d3-transition/src/transition/end.js
function end_default() {
  var on0, on1, that = this, id2 = that._id, size = that.size();
  return new Promise(function(resolve, reject) {
    var cancel = { value: reject }, end = { value: function() {
      if (--size === 0) resolve();
    } };
    that.each(function() {
      var schedule = set2(this, id2), on = schedule.on;
      if (on !== on0) {
        on1 = (on0 = on).copy();
        on1._.cancel.push(cancel);
        on1._.interrupt.push(cancel);
        on1._.end.push(end);
      }
      schedule.on = on1;
    });
    if (size === 0) resolve();
  });
}

// node_modules/d3-transition/src/transition/index.js
var id = 0;
function Transition(groups, parents, name, id2) {
  this._groups = groups;
  this._parents = parents;
  this._name = name;
  this._id = id2;
}
function transition2(name) {
  return selection_default().transition(name);
}
function newId() {
  return ++id;
}
var selection_prototype = selection_default.prototype;
Transition.prototype = transition2.prototype = {
  constructor: Transition,
  select: select_default3,
  selectAll: selectAll_default2,
  selectChild: selection_prototype.selectChild,
  selectChildren: selection_prototype.selectChildren,
  filter: filter_default2,
  merge: merge_default2,
  selection: selection_default2,
  transition: transition_default,
  call: selection_prototype.call,
  nodes: selection_prototype.nodes,
  node: selection_prototype.node,
  size: selection_prototype.size,
  empty: selection_prototype.empty,
  each: selection_prototype.each,
  on: on_default2,
  attr: attr_default2,
  attrTween: attrTween_default,
  style: style_default2,
  styleTween: styleTween_default,
  text: text_default2,
  textTween: textTween_default,
  remove: remove_default2,
  tween: tween_default,
  delay: delay_default,
  duration: duration_default,
  ease: ease_default,
  easeVarying: easeVarying_default,
  end: end_default,
  [Symbol.iterator]: selection_prototype[Symbol.iterator]
};

// node_modules/d3-ease/src/cubic.js
function cubicInOut(t) {
  return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2;
}

// node_modules/d3-transition/src/selection/transition.js
var defaultTiming = {
  time: null,
  // Set on use.
  delay: 0,
  duration: 250,
  ease: cubicInOut
};
function inherit(node, id2) {
  var timing;
  while (!(timing = node.__transition) || !(timing = timing[id2])) {
    if (!(node = node.parentNode)) {
      throw new Error(`transition ${id2} not found`);
    }
  }
  return timing;
}
function transition_default2(name) {
  var id2, timing;
  if (name instanceof Transition) {
    id2 = name._id, name = name._name;
  } else {
    id2 = newId(), (timing = defaultTiming).time = now2(), name = name == null ? null : name + "";
  }
  for (var groups = this._groups, m = groups.length, j = 0; j < m; ++j) {
    for (var group = groups[j], n2 = group.length, node, i = 0; i < n2; ++i) {
      if (node = group[i]) {
        schedule_default(node, name, id2, i, group, timing || inherit(node, id2));
      }
    }
  }
  return new Transition(groups, this._parents, name, id2);
}

// node_modules/d3-transition/src/selection/index.js
selection_default.prototype.interrupt = interrupt_default2;
selection_default.prototype.transition = transition_default2;

// src/axisutil.mts
var LuxonTimeScale = class {
  constructor(interval2, range) {
    checkLuxonValid(interval2);
    this.interval = interval2;
    this.range = range.slice();
  }
  for(d) {
    return this.d3scale(toJSDate(d));
  }
  invert(v) {
    return DateTime.fromJSDate(this.d3scale.invert(v));
  }
  domain() {
    return this.interval;
  }
  get d3scale() {
    checkLuxonValid(this.interval);
    const d3TimeScale = utcTime();
    const s2 = toJSDate(this.interval.start);
    const e = toJSDate(this.interval.end);
    d3TimeScale.domain([s2, e]);
    d3TimeScale.range(this.range);
    return d3TimeScale;
  }
  millisPerPixel() {
    return this.interval.length("milliseconds") / (this.range[1] - this.range[0]);
  }
};
function removeXLabel(svgEl) {
  const svg = select_default2(svgEl);
  svg.selectAll("g.xLabel").remove();
}
function drawXLabel(svgEl, seismographConfig, height, width, handlebarsInput = {}) {
  const svg = select_default2(svgEl);
  svg.selectAll("g.xLabel").remove();
  if (seismographConfig.xLabel && seismographConfig.xLabel.length > 0) {
    const svgText = svg.append("g").classed("xLabel", true).attr(
      "transform",
      `translate(${seismographConfig.margin.left + width / 2}, ${height + seismographConfig.margin.top + seismographConfig.margin.bottom * 2 / 3} )`
    ).append("text").classed("x label", true).attr("text-anchor", "middle").text(seismographConfig.xLabel);
    const handlebarOut = seismographConfig.handlebarsXLabel(handlebarsInput, {
      allowProtoPropertiesByDefault: true
      // this might be a security issue???
    });
    svgText.html(handlebarOut);
  }
}
function removeXSublabel(svgEl) {
  const svg = select_default2(svgEl);
  svg.selectAll("g.xSublabel").remove();
}
function drawXSublabel(svgEl, seismographConfig, height, width, handlebarsInput = {}) {
  const svg = select_default2(svgEl);
  svg.selectAll("g.xSublabel").remove();
  const svgText = svg.append("g").classed("xSublabel", true).attr(
    "transform",
    `translate(${seismographConfig.margin.left + width / 2}, ${height + seismographConfig.margin.top + seismographConfig.margin.bottom} )`
  ).append("text").classed("x label sublabel", true).attr("text-anchor", "middle");
  const handlebarOut = seismographConfig.handlebarsXSublabel(handlebarsInput, {
    allowProtoPropertiesByDefault: true
    // this might be a security issue???
  });
  svgText.html(handlebarOut);
}
function removeYLabel(svgEl) {
  const svg = select_default2(svgEl);
  svg.selectAll("g.yLabel").remove();
}
function drawYLabel(svgEl, seismographConfig, height, width, handlebarsInput = {}) {
  const svg = select_default2(svgEl);
  svg.selectAll("g.yLabel").remove();
  for (const side of ["left", "right"]) {
    const hTranslate = side === "left" ? 0 : seismographConfig.margin.left + width + 1;
    const svgText = svg.append("g").classed("yLabel", true).classed(side, true).attr("x", 0).attr(
      "transform",
      `translate(${hTranslate}, ${seismographConfig.margin.top + height / 2})`
    ).append("text");
    svgText.classed("y label", true);
    if (seismographConfig.yLabelOrientation === "vertical") {
      svgText.attr("text-anchor", "middle").attr("dy", ".75em").attr("transform", "rotate(-90, 0, 0)");
    } else {
      if (side === "left") {
        svgText.attr("text-anchor", "start").attr("dominant-baseline", "central");
      } else {
        svgText.attr("text-anchor", "end").attr("dominant-baseline", "central");
        svgText.attr("x", seismographConfig.margin.right - 1);
      }
    }
    if (side === "left") {
      const handlebarOut = seismographConfig.handlebarsYLabel(handlebarsInput, {
        allowProtoPropertiesByDefault: true
        // this might be a security issue???
      });
      svgText.html(handlebarOut);
    } else {
      const handlebarOut = seismographConfig.handlebarsYLabelRight(
        handlebarsInput,
        {
          allowProtoPropertiesByDefault: true
          // this might be a security issue???
        }
      );
      svgText.html(handlebarOut);
    }
  }
}
function removeYSublabel(svgEl) {
  const svg = select_default2(svgEl);
  svg.selectAll("g.ySublabel").remove();
}
function drawYSublabel(svgEl, seismographConfig, height, width, handlebarsInput = {}, unitsLabel = "") {
  const svg = select_default2(svgEl);
  svg.selectAll("g.ySublabel").remove();
  for (const side of ["left", "right"]) {
    const svgText = svg.append("g").classed("ySublabel", true).attr("x", 0).attr(
      "transform",
      `translate( ${seismographConfig.ySublabelTrans}, ${seismographConfig.margin.top + height / 2} )`
    ).append("text").classed("y label sublabel", true);
    if (seismographConfig.yLabelOrientation === "vertical") {
      svgText.attr("text-anchor", "middle").attr("dy", ".75em").attr("transform", "rotate(-90, 0, 0)");
    } else {
      if (side === "left") {
        svgText.attr("text-anchor", "start").attr("dominant-baseline", "central");
      } else {
        svgText.attr("text-anchor", "end").attr("dominant-baseline", "central");
        svgText.attr("x", seismographConfig.margin.right - 1);
      }
    }
    if (seismographConfig.ySublabelIsUnits) {
      svgText.html(unitsLabel);
    } else {
      const handlebarOut = seismographConfig.handlebarsYSublabel(
        handlebarsInput,
        {
          allowProtoPropertiesByDefault: true
          // this might be a security issue???
        }
      );
      svgText.html(handlebarOut);
    }
  }
}
function removeTitle(svgEl) {
  const svg = select_default2(svgEl);
  svg.selectAll("g.title").remove();
}
function drawTitle(svgEl, seismographConfig, height, width, handlebarsInput = {}) {
  if (!svgEl) {
    return;
  }
  let titleG = svgEl.querySelector("g.title");
  if (!seismographConfig.showTitle) {
    if (titleG) {
      svgEl.removeChild(titleG);
    }
    return;
  }
  if (!titleG) {
    titleG = svgEl.appendChild(createSVGElement("g"));
    titleG.setAttribute("class", "title");
  }
  titleG.setAttribute(
    "transform",
    `translate(${seismographConfig.margin.left + width / 2}, 0)`
  );
  let textEl;
  const queryTextEl = titleG.querySelector("text");
  if (!queryTextEl) {
    textEl = createSVGElement("text");
    titleG.appendChild(textEl);
  } else {
    textEl = queryTextEl;
  }
  textEl.setAttribute("class", "title label");
  textEl.setAttribute("x", "0");
  textEl.setAttribute("dy", "0.85em");
  textEl.setAttribute("text-anchor", "middle");
  if (!handlebarsInput.seisConfig) {
    handlebarsInput.seisConfig = seismographConfig;
  }
  const handlebarOut = seismographConfig.handlebarsTitle(handlebarsInput, {
    allowProtoPropertiesByDefault: true
    // this might be a security issue???
  });
  textEl.innerHTML = handlebarOut;
}
function drawAxisLabels(svgEl, seismographConfig, height, width, handlebarsInput = {}, unitsLabel = "") {
  if (!svgEl) {
    return;
  }
  if (!(svgEl instanceof SVGElement)) {
    return;
  }
  drawTitle(svgEl, seismographConfig, height, width, handlebarsInput);
  drawXLabel(svgEl, seismographConfig, height, width, handlebarsInput);
  drawXSublabel(svgEl, seismographConfig, height, width, handlebarsInput);
  drawYLabel(svgEl, seismographConfig, height, width, handlebarsInput);
  drawYSublabel(
    svgEl,
    seismographConfig,
    height,
    width,
    handlebarsInput,
    unitsLabel
  );
}

// src/seismographutil.mts
var DEFAULT_MAX_SAMPLE_PER_PIXEL = 3;
var DEFAULT_GRID_LINE_COLOR = "gainsboro";
function clearCanvas(canvas) {
  canvas.getContext("2d")?.clearRect(0, 0, canvas.width, canvas.height);
}
function drawXScaleGridLines(canvas, xScale, colorname = DEFAULT_GRID_LINE_COLOR, lineWidth = 1) {
  if (canvas.height === 0) {
    return;
  }
  const context = canvas.getContext("2d");
  if (!isDef(context)) {
    throw new Error("canvas 2d context is null, should not happen...");
  }
  let xScaleToDraw;
  if (xScale instanceof LuxonTimeScale) {
    xScaleToDraw = xScale.d3scale;
  } else {
    xScaleToDraw = xScale;
  }
  xScaleToDraw.ticks().forEach((t) => {
    context.beginPath();
    context.strokeStyle = colorname;
    context.lineWidth = lineWidth;
    context.moveTo(xScaleToDraw(t), 0);
    context.lineTo(xScaleToDraw(t), canvas.height);
    context.stroke();
  });
}
function drawYScaleGridLines(canvas, yScale, colorname = DEFAULT_GRID_LINE_COLOR, lineWidth = 1) {
  if (canvas.height === 0) {
    return;
  }
  const context = canvas.getContext("2d");
  if (!isDef(context)) {
    throw new Error("canvas 2d context is null, should not happen...");
  }
  yScale.ticks().forEach((t) => {
    context.beginPath();
    context.strokeStyle = colorname;
    context.lineWidth = lineWidth;
    context.moveTo(0, yScale(t));
    context.lineTo(canvas.width, yScale(t));
    context.stroke();
  });
}
function drawAllOnCanvas(canvas, sddList, xScaleList, yScaleList, colornameList, lineWidth = 1, connectSegments = false, maxSamplePerPixelForLineDraw = DEFAULT_MAX_SAMPLE_PER_PIXEL) {
  if (canvas.height === 0) {
    return;
  }
  const context = canvas.getContext("2d");
  if (!isDef(context)) {
    throw new Error("canvas 2d context is null, should not happen...");
  }
  sddList.forEach((sdd, i) => {
    const xScale = xScaleList[i];
    const yScale = yScaleList[i];
    const s2 = xScale.domain().start?.valueOf();
    const e = xScale.domain().end?.valueOf();
    if (s2 == null || e == null || s2 === e) {
      return;
    } else {
      const seismogram = sdd.seismogram;
      if (!seismogram) {
        return;
      }
      context.save();
      drawSeismogramAsLine(
        sdd,
        context,
        canvas.width,
        xScale,
        yScale,
        colornameList[i],
        lineWidth,
        connectSegments,
        maxSamplePerPixelForLineDraw
      );
      context.restore();
    }
  });
}
function drawSeismogramAsLine(sdd, context, width, xScale, yScale, color2, lineWidth = 1, connectSegments = false, maxSamplePerPixelForLineDraw = DEFAULT_MAX_SAMPLE_PER_PIXEL) {
  const seismogram = sdd.seismogram;
  if (!seismogram) {
    return;
  }
  let firstTime = true;
  const s2 = xScale.domain().start?.valueOf();
  const e = xScale.domain().end?.valueOf();
  if (s2 == null || e == null) {
    throw new Error(`Bad xscale domain: ${String(xScale.domain())}`);
  }
  if (xScale.for(seismogram.startTime) > xScale.range[1] || xScale.for(seismogram.endTime) < xScale.range[0]) {
    return;
  }
  seismogram.segments.forEach((segment) => {
    const drawSeg = seismogramSegmentAsLine(
      segment,
      width,
      xScale,
      yScale,
      maxSamplePerPixelForLineDraw
    );
    if (firstTime || !connectSegments) {
      context.beginPath();
      context.strokeStyle = color2;
      context.lineWidth = lineWidth;
      context.moveTo(drawSeg.x[0], drawSeg.y[0]);
      firstTime = false;
    }
    for (let i = 0; i < drawSeg.x.length; i++) {
      context.lineTo(drawSeg.x[i], drawSeg.y[i]);
    }
    if (!connectSegments) {
      context.stroke();
    }
  });
  if (!firstTime && connectSegments) {
    context.stroke();
  }
}
function seismogramSegmentAsLine(segment, width, xScale, yScale, maxSamplePerPixelForLineDraw = DEFAULT_MAX_SAMPLE_PER_PIXEL) {
  const out = {
    x: [],
    y: [],
    samplesPerPixel: 0,
    maxSamplePerPixelForLineDraw
  };
  if (!segment) {
    return out;
  }
  const s2 = xScale.domain().start?.valueOf();
  const e = xScale.domain().end?.valueOf();
  if (s2 == null || e == null) {
    throw new Error(`Bad xscale domain: ${String(xScale.domain())}`);
  }
  if (xScale.for(segment.startTime) > xScale.range[1] || xScale.for(segment.endTime) < xScale.range[0]) {
    return out;
  }
  const secondsPerPixel = (e - s2) / 1e3 / (xScale.range[1] - xScale.range[0]);
  const samplesPerPixel = 1 * segment.sampleRate * secondsPerPixel;
  out.samplesPerPixel = samplesPerPixel;
  out.maxSamplePerPixelForLineDraw = maxSamplePerPixelForLineDraw;
  const pixelsPerSample = 1 / samplesPerPixel;
  const startPixel = xScale.for(segment.startTime);
  const endPixel = xScale.for(segment.endTime);
  let leftVisibleSample = 0;
  let rightVisibleSample = segment.y.length;
  let leftVisiblePixel = startPixel;
  if (startPixel < 0) {
    leftVisibleSample = Math.floor(-1 * startPixel * samplesPerPixel);
    leftVisiblePixel = 0;
  }
  if (endPixel > xScale.range[1] + 1) {
    rightVisibleSample = leftVisibleSample + Math.ceil((width + 1) * samplesPerPixel) + 2;
  }
  if (samplesPerPixel <= maxSamplePerPixelForLineDraw) {
    for (let i = leftVisibleSample; i < rightVisibleSample + 2 && i < segment.y.length; i++) {
      pushPoint(
        out,
        Math.round(xScale.for(segment.timeOfSample(i))),
        Math.round(yScale(segment.y[i]))
      );
    }
  } else {
    let prevLastYPixel = Math.round(yScale(segment.y[leftVisibleSample]));
    let lastYPixel;
    pushPoint(out, leftVisiblePixel, prevLastYPixel);
    let i = leftVisibleSample;
    let inHorizontalLine = false;
    while (i < rightVisibleSample + 2 && i < segment.y.length) {
      const curPixel = Math.floor(startPixel + i * pixelsPerSample);
      let min = segment.y[i];
      let max = segment.y[i];
      let minIdx = i;
      let maxIdx = i;
      const firstYPixel = Math.round(yScale(segment.y[i]));
      while (curPixel === Math.floor(startPixel + i * pixelsPerSample)) {
        if (min > segment.y[i]) {
          min = segment.y[i];
          minIdx = i;
        }
        if (max < segment.y[i]) {
          max = segment.y[i];
          maxIdx = i;
        }
        i++;
      }
      lastYPixel = Math.round(yScale(segment.y[i - 1]));
      const topPixelFlt = yScale(max);
      const botPixelFlt = yScale(min);
      const botPixel = Math.round(botPixelFlt);
      const topPixel = Math.round(topPixelFlt);
      if (topPixel === botPixel) {
        if (prevLastYPixel === topPixel) {
          inHorizontalLine = true;
          continue;
        } else {
          if (inHorizontalLine) {
            pushPoint(out, curPixel - 1, prevLastYPixel);
          }
          pushPoint(out, curPixel, firstYPixel);
          inHorizontalLine = false;
        }
      } else {
        if (inHorizontalLine) {
          pushPoint(out, curPixel - 1, prevLastYPixel);
        }
        inHorizontalLine = false;
        if (minIdx < maxIdx) {
          if (firstYPixel !== botPixel) {
            pushPoint(out, curPixel, firstYPixel);
          }
          pushPoint(out, curPixel, botPixel);
          pushPoint(out, curPixel, topPixel);
          if (lastYPixel !== topPixel) {
            pushPoint(out, curPixel, lastYPixel);
          }
        } else {
          if (firstYPixel !== topPixel) {
            pushPoint(out, curPixel, firstYPixel);
          }
          pushPoint(out, curPixel, topPixel);
          pushPoint(out, curPixel, botPixel);
          if (lastYPixel !== botPixel) {
            pushPoint(out, curPixel, lastYPixel);
          }
        }
      }
      prevLastYPixel = lastYPixel;
    }
    if (inHorizontalLine || i < segment.y.length) {
      if (i >= segment.y.length) {
        i = segment.y.length - 1;
      }
      const curPixel = Math.floor(startPixel + i * pixelsPerSample);
      lastYPixel = Math.round(yScale(segment.y[i]));
      pushPoint(out, curPixel, lastYPixel);
    }
  }
  return out;
}
function pushPoint(out, xpixel, ypixel) {
  out.x.push(xpixel);
  out.y.push(ypixel);
}
function rgbaForColorName(name) {
  const out = new Uint8ClampedArray(4);
  const ctx = document.createElement("canvas").getContext("2d");
  if (!ctx) {
    return out;
  }
  ctx.fillStyle = name;
  const color_rgb = ctx.fillStyle.substring(1);
  out[0] = Number.parseInt(`0x${color_rgb.substring(0, 2)}`, 16);
  out[1] = Number.parseInt(`0x${color_rgb.substring(2, 4)}`, 16);
  out[2] = Number.parseInt(`0x${color_rgb.substring(4, 6)}`, 16);
  out[3] = 255;
  return out;
}

// src/handlebarshelpers.mts
var handlebarshelpers_exports = {};
__export(handlebarshelpers_exports, {
  Handlebars: () => import_handlebars.default,
  registerHelpers: () => registerHelpers
});
var import_handlebars = __toESM(require_handlebars(), 1);
function registerHelpers() {
  import_handlebars.default.registerHelper(
    "onlyChangesChannel",
    function(sddDataList, index) {
      let out;
      const curr = sddDataList[index];
      if (typeof curr === "undefined" || curr === null) {
        return "unknown";
      }
      if (index === 0) {
        out = curr.codes();
      } else {
        const prev = sddDataList[index - 1];
        if (prev.networkCode !== curr.networkCode) {
          out = curr.codes();
        } else if (prev.stationCode !== curr.stationCode) {
          out = `${curr.stationCode}.${curr.locationCode}.${curr.channelCode}`;
        } else if (prev.locationCode !== curr.locationCode) {
          out = `${curr.locationCode}.${curr.channelCode}`;
        } else {
          out = curr.channelCode;
        }
      }
      return out;
    }
  );
  import_handlebars.default.registerHelper("distdeg", function(sdd) {
    const distaz2 = sdd.distaz;
    if (distaz2) {
      return distaz2.distanceDeg;
    } else {
      return "";
    }
  });
  import_handlebars.default.registerHelper("distkm", function(sdd) {
    const distaz2 = sdd.distaz;
    if (distaz2) {
      return distaz2.distanceKm;
    } else {
      return "";
    }
  });
  import_handlebars.default.registerHelper("formatNumber", function(val, digits = 2) {
    if (typeof val === "undefined" || val === null) {
      return "";
    }
    if (typeof digits === "string") {
      digits = parseInt(digits);
    }
    if (typeof val === "number" && typeof digits === "number") {
      return val.toFixed(digits);
    }
    return val;
  });
  import_handlebars.default.registerHelper(
    "formatIsoDate",
    function(param, hash2) {
      if (typeof param === "undefined" || param === null) return "no time";
      let m = param;
      if (!DateTime.isDateTime(param)) {
        m = checkStringOrDate(param);
      }
      if ("format" in hash2 && typeof hash2.format === "string") {
        return m.toFormat(hash2.format);
      } else {
        return m.toISO();
      }
    }
  );
  import_handlebars.default.registerHelper(
    "formatDuration",
    function(param) {
      if (typeof param === "undefined" || param === null) return "no time";
      if (Interval.isInterval(param)) {
        param = param.toDuration();
      }
      if (!Duration.isDuration(param)) {
        return `${String(param)}`;
      }
      return `${param.toMillis() / 1e3} sec`;
    }
  );
}

// src/seismographconfig.mts
registerHelpers();
var DEFAULT_TITLE = "{{#each seisDataList}}<tspan>{{onlyChangesChannel ../seisDataList @index}}</tspan> {{else}}No Data{{/each}}";
var SeismographConfigCache = class {
  constructor() {
    this.titleHandlebarsCompiled = null;
    this.xLabelHandlebarsCompiled = null;
    this.xSublabelHandlebarsCompiled = null;
    this.yLabelHandlebarsCompiled = null;
    this.yLabelRightHandlebarsCompiled = null;
    this.ySublabelHandlebarsCompiled = null;
  }
};
var SeismographConfig = class _SeismographConfig {
  constructor() {
    this.configId = ++_SeismographConfig._lastID;
    this.__cache__ = new SeismographConfigCache();
    this.isXAxis = true;
    this.isXAxisTop = false;
    this.xAxisTimeZone = null;
    this.isYAxisNice = true;
    this.isYAxis = true;
    this.isYAxisRight = false;
    this.yAxisNumTickHint = 8;
    this.xGridLines = false;
    this.yGridLines = false;
    this.gridLineColor = DEFAULT_GRID_LINE_COLOR;
    this._timeFormat = null;
    this.relativeTimeFormat = formatCountOrAmp;
    this.amplitudeFormat = formatCountOrAmp;
    this._title = [DEFAULT_TITLE];
    this.showTitle = true;
    this._xLabel = "Time";
    this.xLabelOrientation = "horizontal";
    this._xSublabel = "";
    this.xSublabelIsUnits = false;
    this._yLabel = "Amplitude";
    this._yLabelRight = "";
    this.yLabelOrientation = "vertical";
    this._ySublabel = "";
    this.ySublabelTrans = 15;
    this.ySublabelIsUnits = true;
    this.amplitudeMode = "minmax" /* MinMax */;
    this.doGain = true;
    this.windowAmp = true;
    this.resolutionScale = 2;
    this._fixedAmplitudeScale = null;
    this._fixedTimeScale = null;
    this._linkedAmplitudeScale = new IndividualAmplitudeScale();
    this._linkedTimeScale = new LinkedTimeScale(
      [],
      Duration.fromMillis(0),
      Duration.fromMillis(0),
      this.configId
    );
    this.isRelativeTime = false;
    this.doMarkers = true;
    this.markerTextOffset = 0.85;
    this.markerTextAngle = 45;
    this.markerFlagpoleBase = "bottom";
    this.minHeight = 0;
    this.maxHeight = null;
    this.minWidth = 0;
    this.maxWidth = null;
    this.margin = {
      top: 25,
      right: 20,
      bottom: 42,
      left: 85,
      toString: function() {
        return `t: ${this.top} l: ${this.left} b: ${this.bottom} r: ${this.right}`;
      }
    };
    this.segmentDrawCompressedCutoff = 10;
    this.maxZoomPixelPerSample = 20;
    this.wheelZoom = false;
    this.allowZoom = true;
    this.connectSegments = false;
    this.lineColors = [
      "skyblue",
      "olivedrab",
      "goldenrod",
      "firebrick",
      "darkcyan",
      "chocolate",
      "darkmagenta",
      "mediumseagreen",
      "rebeccapurple",
      "sienna",
      "orchid",
      "royalblue",
      "mediumturquoise",
      "chartreuse",
      "peru",
      "black"
    ];
    this.lineWidth = 1;
  }
  static fromJSON(json2) {
    const seisConfig = new _SeismographConfig();
    const tempJson = {};
    Object.assign(tempJson, json2);
    if (Object.hasOwn(tempJson, "fixedAmplitudeScale")) {
      delete tempJson.fixedAmplitudeScale;
    }
    if (Object.hasOwn(tempJson, "fixedTimeScale")) {
      delete tempJson.fixedTimeScale;
    }
    if (Object.hasOwn(tempJson, "isLinkedTimeScale")) {
      delete tempJson.isLinkedTimeScale;
    }
    if (Object.hasOwn(tempJson, "isLinkedAmplitudeScale")) {
      delete tempJson.isLinkedAmplitudeScale;
    }
    if (Object.hasOwn(tempJson, "xAxisTimeZone")) {
      delete tempJson.xAxisTimeZone;
    }
    if (Object.hasOwn(tempJson, "ySublabel") && // @ts-expect-error ok as we just check hasOwn
    tempJson.ySublabel.length === 0) {
      delete tempJson.ySublabel;
    }
    Object.assign(seisConfig, tempJson);
    if (json2.isLinkedTimeScale) {
      seisConfig.linkedTimeScale = new LinkedTimeScale();
    } else {
      seisConfig.fixedAmplitudeScale = json2.fixedAmplitudeScale;
    }
    if (json2.isLinkedAmplitudeScale) {
      seisConfig.linkedAmplitudeScale = new LinkedAmplitudeScale();
    } else if (isDef(json2.fixedAmplitudeScale)) {
      seisConfig.fixedAmplitudeScale = json2.fixedAmplitudeScale;
    } else {
      seisConfig.linkedAmplitudeScale = new IndividualAmplitudeScale();
    }
    if (json2.xAxisTimeZone) {
      seisConfig.xAxisTimeZone = new IANAZone(json2.xAxisTimeZone);
    }
    return seisConfig;
  }
  asJSON() {
    const out = JSON.parse(JSON.stringify(this));
    out.title = out._title;
    delete out._title;
    out.xAxisTimeZone = isDef(this.xAxisTimeZone) ? isStringArg(this.xAxisTimeZone) ? this.xAxisTimeZone : this.xAxisTimeZone.name : null;
    out.fixedAmplitudeScale = out._fixedAmplitudeScale;
    delete out._fixedAmplitudeScale;
    out.fixedTimeScale = out._fixedTimeScale;
    delete out._fixedTimeScale;
    delete out._linkedTimeScale;
    out.isLinkedTimeScale = isDef(this._linkedTimeScale);
    out.isLinkedAmplitudeScale = isDef(this._linkedAmplitudeScale) && !(this._linkedAmplitudeScale instanceof IndividualAmplitudeScale);
    delete out._linkedAmplitudeScale;
    delete out.__cache__;
    Object.getOwnPropertyNames(out).forEach((p) => {
      if (p.startsWith("_")) {
        const tmp = out[p];
        delete out[p];
        out[p.substring(1)] = tmp;
      }
    });
    return out;
  }
  get fixedAmplitudeScale() {
    return this._fixedAmplitudeScale;
  }
  set fixedAmplitudeScale(ts) {
    if (!isDef(ts)) {
      throw new Error("amp scale must be defined setting fixed");
    }
    this._fixedAmplitudeScale = ts;
    this._linkedAmplitudeScale = null;
  }
  get linkedAmplitudeScale() {
    return this._linkedAmplitudeScale;
  }
  set linkedAmplitudeScale(ts) {
    if (!isDef(ts)) {
      throw new Error("amp scale must be defined setting linked");
    }
    if (this._linkedAmplitudeScale) {
      ts.linkAll(this._linkedAmplitudeScale.graphList);
    }
    this._linkedAmplitudeScale = ts;
    this._fixedAmplitudeScale = null;
  }
  /**
   * Enable linked amplitude scales across seismographs.
   *
   */
  enableLinkedAmplitude() {
    this.linkedAmplitudeScale = new LinkedAmplitudeScale();
  }
  /**
   * Set Raw amplitude mode, plot absolute and
   * goes from minimun to maximum of data
   */
  amplitudeRaw() {
    this.amplitudeMode = "raw" /* Raw */;
  }
  /**
   * Set MinMax amplitude mode, plot is relative and
   * centered on (minimun + maximum)/2
   */
  amplitudeMinMax() {
    this.amplitudeMode = "minmax" /* MinMax */;
  }
  /**
   * Set Mean amplitude mode, plot is relative and
   * centered on mean of data
   */
  amplitudeMean() {
    this.amplitudeMode = "mean" /* Mean */;
  }
  /**
   * Set WithZero amplitude mode, plot is absolute and
   * centered on mean of data like Raw, but also includes zero
   * even if all data is positive. Useful when showing
   * data compared to zero is helpful.
   */
  amplitudeWithZero() {
    this.amplitudeMode = "zero" /* Zero */;
  }
  /**
   * True if the amplitude is "centered".
   *
   * Both MinMax and Mean center the amplitude, Raw and Zero do not.
   *
   * @returns if centered
   */
  isCenteredAmp() {
    return this.amplitudeMode === "minmax" /* MinMax */ || this.amplitudeMode === "mean" /* Mean */;
  }
  get fixedTimeScale() {
    return this._fixedTimeScale;
  }
  set fixedTimeScale(ts) {
    if (!isDef(ts)) {
      throw new Error("time scale must be defined");
    }
    this._fixedTimeScale = ts;
    this._linkedTimeScale = null;
  }
  get linkedTimeScale() {
    return this._linkedTimeScale;
  }
  set linkedTimeScale(ts) {
    if (!isDef(ts)) {
      throw new Error("time scale must be defined");
    }
    if (this._linkedTimeScale) {
      ts.linkAll(this._linkedTimeScale.graphList);
    }
    this._linkedTimeScale = ts;
    this._fixedTimeScale = null;
  }
  /**
   * Configures the time axis to show times in the given time zone. This
   * replaces timeFormat with createTimeFormatterForZone() and
   * sets xSublabel to be the zone name. If zone is null, uses UTC.
   *
   * @param  zone string like "US/Eastern" or luxon Zone
   */
  enableXAxisTimeZone(zone) {
    let zoneName;
    let tz;
    if (isStringArg(zone)) {
      zoneName = zone;
      tz = new IANAZone(zone);
    } else if (zone instanceof Zone) {
      tz = zone;
      zoneName = nameForTimeZone(tz.name);
    } else {
      tz = FixedOffsetZone.utcInstance;
      zoneName = "UTC";
    }
    this.timeFormat = createTimeFormatterForZone(tz);
    this.xSublabel = zoneName;
  }
  /**
   * Time formatter used by the x axis. Defaults to UTC via
   * createTimeFormatterForZone(zone).
   * Set xAxisTimeZone to change the time zone.
   * @return formatter for x axis time labels
   */
  get timeFormat() {
    let tz;
    if (this._timeFormat != null) {
      return this._timeFormat;
    } else if (isStringArg(this.xAxisTimeZone)) {
      tz = new IANAZone(this.xAxisTimeZone);
    } else if (this.xAxisTimeZone instanceof Zone) {
      tz = this.xAxisTimeZone;
    } else {
      tz = FixedOffsetZone.utcInstance;
    }
    return createTimeFormatterForZone(tz);
  }
  set timeFormat(formatter) {
    this._timeFormat = formatter;
  }
  /**
   * gets the current title
   *
   * @returns        title as an array of strings
   */
  get title() {
    return this._title;
  }
  /**
   * Sets the title as simple string or array of strings or a
   * handlebars template. If an array
   * then each item will be in a separate tspan for easier formatting.
   *
   * @param value string or array of strings to be the title
   */
  set title(value) {
    if (!isDef(value)) {
      this._title = [""];
    } else if (Array.isArray(value)) {
      this._title = value;
    } else {
      this._title = [value];
    }
    this.__cache__.titleHandlebarsCompiled = null;
  }
  handlebarsTitle(context, runtimeOptions) {
    if (!isDef(this.__cache__.titleHandlebarsCompiled)) {
      if (!isDef(this._title) || this._title.length === 0 || !isDef(this._title[0])) {
        return "";
      } else if (this._title.length === 1) {
        this.__cache__.titleHandlebarsCompiled = import_handlebars.default.compile(
          this._title[0]
        );
      } else {
        this.__cache__.titleHandlebarsCompiled = import_handlebars.default.compile(
          "" + this._title.join(" ")
        );
      }
    }
    if (!this.__cache__.titleHandlebarsCompiled) {
      throw new Error(
        `Unable to compile handlebars title for ${stringify(this._title)}`
      );
    }
    return this.__cache__.titleHandlebarsCompiled(context, runtimeOptions);
  }
  /**
   * gets the current x label
   *
   * @returns        x label
   */
  get xLabel() {
    return this._xLabel;
  }
  /**
   * Sets the xLabel as simple string or a
   * handlebars template.
   *
   * @param value string  to be the x label
   */
  set xLabel(value) {
    if (!isDef(value)) {
      this._xLabel = "";
    } else {
      this._xLabel = value;
    }
    this.__cache__.xLabelHandlebarsCompiled = null;
  }
  /**
   * gets the current x sublabel
   *
   * @returns        x sublabel
   */
  get xSublabel() {
    return this._xSublabel;
  }
  /**
   * Sets the xSublabel as simple string or a
   * handlebars template.
   *
   * @param value string  to be the x sublabel
   */
  set xSublabel(value) {
    if (!isDef(value)) {
      this._xSublabel = "";
    } else {
      this._xSublabel = value;
    }
    this.__cache__.xSublabelHandlebarsCompiled = null;
  }
  handlebarsXLabel(context, runtimeOptions) {
    if (!isDef(this.__cache__.xLabelHandlebarsCompiled)) {
      if (!isDef(this._xLabel) || this._xLabel.length === 0) {
        return "";
      } else {
        this.__cache__.xLabelHandlebarsCompiled = import_handlebars.default.compile(
          this._xLabel
        );
      }
    }
    if (!this.__cache__.xLabelHandlebarsCompiled) {
      throw new Error(
        `Unable to compile handlebars xLabel for ${this._xLabel}`
      );
    }
    return this.__cache__.xLabelHandlebarsCompiled(context, runtimeOptions);
  }
  handlebarsXSublabel(context, runtimeOptions) {
    if (!isDef(this.__cache__.xSublabelHandlebarsCompiled)) {
      if (!isDef(this._xSublabel) || this._xSublabel.length === 0) {
        return "";
      } else {
        this.__cache__.xSublabelHandlebarsCompiled = import_handlebars.default.compile(
          this._xSublabel
        );
      }
    }
    if (!this.__cache__.xSublabelHandlebarsCompiled) {
      throw new Error(
        `Unable to compile handlebars xLabel for ${this._xSublabel}`
      );
    }
    return this.__cache__.xSublabelHandlebarsCompiled(context, runtimeOptions);
  }
  /**
   * gets the current y label
   *
   * @returns        yLabel
   */
  get yLabel() {
    return this._yLabel;
  }
  /**
   * Sets the ylabel as simple string or a
   * handlebars template.
   *
   * @param value string to be the y label
   */
  set yLabel(value) {
    if (!isDef(value)) {
      this._yLabel = "";
    } else {
      this._yLabel = value;
    }
    this.__cache__.yLabelHandlebarsCompiled = null;
  }
  /**
   * gets the current y sublabel
   *
   * @returns        ySublabel
   */
  get ySublabel() {
    return this._ySublabel;
  }
  /**
   * Sets the y sublabel as simple string or a
   * handlebars template.
   *
   * @param value string to be the y sublabel
   */
  set ySublabel(value) {
    if (!isDef(value)) {
      this._ySublabel = "";
    } else {
      this._ySublabel = value;
    }
    this.ySublabelIsUnits = false;
    this.__cache__.ySublabelHandlebarsCompiled = null;
  }
  handlebarsYLabel(context, runtimeOptions) {
    if (!isDef(this.__cache__.yLabelHandlebarsCompiled)) {
      if (!isDef(this._yLabel) || this._yLabel.length === 0) {
        return "";
      } else {
        this.__cache__.yLabelHandlebarsCompiled = import_handlebars.default.compile(
          this._yLabel
        );
      }
    }
    if (!this.__cache__.yLabelHandlebarsCompiled) {
      throw new Error(
        `Unable to compile handlebars yLabel for ${this._yLabel}`
      );
    }
    return this.__cache__.yLabelHandlebarsCompiled(context, runtimeOptions);
  }
  handlebarsYSublabel(context, runtimeOptions) {
    if (!isDef(this.__cache__.ySublabelHandlebarsCompiled)) {
      if (!isDef(this._ySublabel) || this._ySublabel.length === 0) {
        return "";
      } else {
        this.__cache__.ySublabelHandlebarsCompiled = import_handlebars.default.compile(
          this._ySublabel
        );
      }
    }
    if (!this.__cache__.ySublabelHandlebarsCompiled) {
      throw new Error(
        `Unable to compile handlebars yLabel for ${this._ySublabel}`
      );
    }
    return this.__cache__.ySublabelHandlebarsCompiled(context, runtimeOptions);
  }
  /**
   * gets the current title
   *
   * @returns        yLabel
   */
  get yLabelRight() {
    return this._yLabelRight;
  }
  /**
   * Sets the ylabel as simple string or a
   * handlebars template.
   *
   * @param value string to be the y label
   */
  set yLabelRight(value) {
    if (!isDef(value)) {
      this._yLabelRight = "";
    } else {
      this._yLabelRight = value;
    }
    this.__cache__.yLabelRightHandlebarsCompiled = null;
  }
  handlebarsYLabelRight(context, runtimeOptions) {
    if (!isDef(this.__cache__.yLabelRightHandlebarsCompiled)) {
      if (!isDef(this._yLabelRight) || this._yLabelRight.length === 0) {
        return "";
      } else {
        this.__cache__.yLabelRightHandlebarsCompiled = import_handlebars.default.compile(
          this._yLabelRight
        );
      }
    }
    if (!this.__cache__.yLabelRightHandlebarsCompiled) {
      throw new Error(
        `Unable to compile handlebars yLabelRight for ${this._yLabelRight}`
      );
    }
    return this.__cache__.yLabelRightHandlebarsCompiled(
      context,
      runtimeOptions
    );
  }
  /**
   * Fake data to use to test alignment of seismograph axis and between canvas
   *  and svg drawing.
   *
   * @param   timeRange start and end of fake data
   * @param   min        min amplitude for fake data, default is -100
   * @param   max        max amplitude for fake data, default is 100
   * @returns             fake data
   */
  createAlignmentData(timeRange, min = -100, max = 100) {
    const mid = (max + min) / 2;
    const fakeData = Float32Array.from([
      max,
      min,
      max,
      min,
      mid,
      mid,
      max,
      mid,
      mid,
      min
    ]);
    const fakeSampleRate = 1 / (1e3 * timeRange.toDuration().toMillis() / (fakeData.length - 1));
    const fakeSeis = Seismogram.fromContiguousData(
      fakeData,
      fakeSampleRate,
      validStartTime(timeRange)
    );
    const fakeSDD = SeismogramDisplayData.fromSeismogram(fakeSeis);
    return fakeSDD;
  }
  getColorForIndex(i) {
    if (isDef(this.lineColors) && this.lineColors.length > 0) {
      return this.lineColors[i % this.lineColors.length];
    } else {
      return "black";
    }
  }
  createCSSForLineColors(svgClass) {
    let cssText = "";
    const numColors = this.lineColors.length;
    let svgEl = "svg";
    if (!isDef(svgClass)) {
      svgEl = `svg.${AUTO_COLOR_SELECTOR}`;
    } else if (svgClass.length === 0) {
      svgEl = "svg";
    } else {
      svgEl = `svg.${svgClass}`;
    }
    cssText = cssText + `
      ${svgEl} g.${G_DATA_SELECTOR} g path {
        fill: none;
        stroke-width: 1px;
      }
    `;
    this.lineColors.forEach((color2, index) => {
      cssText = cssText + `
        ${svgEl} g.title  text tspan:nth-child(${numColors}n+${index + 1})  {
          stroke: ${color2};
          fill: ${color2};
          color: ${color2};
        }
        `;
      cssText += `
        ${svgEl} g.${G_DATA_SELECTOR} g:nth-child(${numColors}n+${index + 1}) path {
          stroke: ${color2};
        }
        `;
    });
    return cssText;
  }
  clone() {
    const out = new _SeismographConfig();
    Object.getOwnPropertyNames(this).forEach((name) => {
      if (Array.isArray(this[name])) {
        out[name] = this[name].slice();
      } else {
        out[name] = this[name];
      }
      out.margin = {
        top: this.margin.top,
        right: this.margin.right,
        bottom: this.margin.bottom,
        left: this.margin.left,
        toString: function() {
          return "t:" + this.top + " l:" + this.left + " b:" + this.bottom + " r:" + this.right;
        }
      };
    });
    out.__cache__ = new SeismographConfigCache();
    return out;
  }
  toString() {
    let outS = "";
    Object.getOwnPropertyNames(this).forEach((name) => {
      outS += `  seisConfig.${name} = ${JSON.stringify(this[name])}
`;
    });
    return outS;
  }
};
function numberFormatWrapper(formater) {
  return function(domainValue) {
    if (typeof domainValue === "number") {
      return formater(domainValue);
    } else {
      throw new Error("Can only format number, " + stringify(domainValue));
    }
  };
}
var formatCount = format("~s");
var formatExp = format(".2e");
var formatCountOrAmp = function(v) {
  return -1 < v && v < 1 && v !== 0 ? formatExp(v) : formatCount(v);
};
function createTimeFormatterForZone(timezone) {
  return (date6) => {
    if (timezone == null) {
      timezone = FixedOffsetZone.utcInstance;
    }
    const dt = DateTime.fromJSDate(date6, { zone: timezone });
    if (dt.millisecond !== 0) {
      return dt.toFormat(".SSS");
    } else if (dt.second !== 0) {
      return dt.toFormat(":ss");
    } else if (dt.minute !== 0) {
      return dt.toFormat("HH:mm");
    } else if (dt.hour !== 0) {
      return dt.toFormat("HH:mm");
    } else if (dt.day !== 0) {
      return dt.toFormat("LL/dd");
    } else if (dt.month !== 0) {
      return dt.toFormat("yyyy/LL");
    } else {
      return dt.toFormat("yyyy");
    }
  };
}
SeismographConfig._lastID = 0;

// src/sorting.mts
var sorting_exports = {};
__export(sorting_exports, {
  SORT_ALPHABETICAL: () => SORT_ALPHABETICAL,
  SORT_AZIMUTH: () => SORT_AZIMUTH,
  SORT_BACKAZIMUTH: () => SORT_BACKAZIMUTH,
  SORT_DISTANCE: () => SORT_DISTANCE,
  SORT_NONE: () => SORT_NONE,
  SORT_ORIGINTIME: () => SORT_ORIGINTIME,
  SORT_STARTTIME: () => SORT_STARTTIME,
  createDefaultSortingOptions: () => createDefaultSortingOptions,
  createSortValueFunction: () => createSortValueFunction,
  reorderXYZ: () => reorderXYZ,
  sort: () => sort,
  sortByFunction: () => sortByFunction
});
var SORT_NONE = "none";
var SORT_DISTANCE = "distance";
var SORT_AZIMUTH = "azimuth";
var SORT_BACKAZIMUTH = "backazimuth";
var SORT_ALPHABETICAL = "alphabetical";
var SORT_STARTTIME = "starttime";
var SORT_ORIGINTIME = "origin";
function sort(seisData, key) {
  if (key === SORT_NONE) {
    return seisData;
  }
  return sortByFunction(seisData, createSortValueFunction(key));
}
function sortByFunction(seisData, sortableFunction) {
  const cache = /* @__PURE__ */ new Map();
  seisData.forEach((sdd) => {
    cache.set(sdd, sortableFunction(sdd));
  });
  return seisData.slice().sort((sddA, sddB) => {
    const valA = cache.get(sddA);
    const valB = cache.get(sddB);
    if (!valA && !valB) {
      return 0;
    } else if (!valA) {
      return 1;
    } else if (!valB) {
      return -1;
    } else if (valA < valB) {
      return -1;
    } else if (valA > valB) {
      return 1;
    } else {
      return 0;
    }
  });
}
function createDefaultSortingOptions() {
  const out = /* @__PURE__ */ new Map();
  out.set(SORT_DISTANCE, createSortValueFunction(SORT_DISTANCE));
  out.set(SORT_AZIMUTH, createSortValueFunction(SORT_AZIMUTH));
  out.set(SORT_BACKAZIMUTH, createSortValueFunction(SORT_BACKAZIMUTH));
  out.set(SORT_ALPHABETICAL, createSortValueFunction(SORT_ALPHABETICAL));
  out.set(SORT_STARTTIME, createSortValueFunction(SORT_STARTTIME));
  out.set(SORT_ORIGINTIME, createSortValueFunction(SORT_ORIGINTIME));
  return out;
}
function createSortValueFunction(key) {
  if (key === SORT_DISTANCE) {
    return (sdd) => {
      let out = Number.MAX_VALUE;
      if (sdd.hasQuake() && sdd.hasChannel()) {
        const distaz2 = sdd.distaz;
        out = distaz2 ? Math.min(Number.MAX_VALUE, distaz2.delta) : Number.MAX_VALUE;
      }
      return out;
    };
  } else if (key === SORT_AZIMUTH) {
    return (sdd) => {
      let out = Number.MAX_VALUE;
      if (sdd.hasQuake() && sdd.hasChannel()) {
        const distaz2 = sdd.distaz;
        out = distaz2 ? Math.min(Number.MAX_VALUE, distaz2.az) : Number.MAX_VALUE;
      }
      return out;
    };
  } else if (key === SORT_BACKAZIMUTH) {
    return (sdd) => {
      let out = Number.MAX_VALUE;
      if (sdd.hasQuake() && sdd.hasChannel()) {
        const distaz2 = sdd.distaz;
        out = distaz2 ? Math.min(Number.MAX_VALUE, distaz2.baz) : Number.MAX_VALUE;
      }
      return out;
    };
  } else if (key === SORT_ALPHABETICAL) {
    return (sdd) => sdd.sourceId.toString();
  } else if (key === SORT_STARTTIME) {
    return (sdd) => sdd.startTime;
  } else if (key === SORT_ORIGINTIME) {
    return (sdd) => {
      let out = WAY_FUTURE;
      if (sdd.hasQuake()) {
        out = sdd.quake ? sdd.quake.time : out;
      }
      return out;
    };
  } else {
    throw new Error(`unknown sorting key: ${key}`);
  }
}
function xyzCompareFun(a, b) {
  if (a.hasChannel() && b.hasChannel()) {
    if (Math.abs(a.channel.dip) > 85 || Math.abs(b.channel.dip) > 85) {
      if (a.channel.dip !== b.channel.dip) {
        return Math.abs(a.channel.dip) - Math.abs(b.channel.dip);
      }
    }
    const ninetyRot = Math.abs(
      (a.channel.azimuth - b.channel.azimuth + 90) % 360
    );
    if (ninetyRot < 5 || ninetyRot > 355) {
      return 1;
    }
    if (ninetyRot > 175 || ninetyRot < 185) {
      return -1;
    }
  }
  const aSID = a.sourceId;
  const bSID = b.sourceId;
  if (aSID && bSID) {
    return aSID.subsourceCode.localeCompare(bSID.subsourceCode);
  } else if (aSID === bSID) {
    return 0;
  } else {
    return -1;
  }
}
function reorderXYZ(sddList) {
  return sddList.slice().sort(xyzCompareFun);
}

// src/spelement.mts
var SORT_BY = "sort";
var SeisPlotElement = class extends HTMLElement {
  constructor(seisData, seisConfig) {
    super();
    this.onRedraw = (_el) => {
    };
    this._throttleRedraw = null;
    if (isDef(seisData)) {
      if (seisData instanceof SeismogramDisplayData) {
        this._seisDataList = [seisData];
      } else if (Array.isArray(seisData) && (seisData.length === 0 || seisData[0] instanceof SeismogramDisplayData)) {
        this._seisDataList = seisData;
      } else {
        let msg = `length: ${seisData.length}  `;
        if (seisData.length > 0) {
          msg = `${msg} ${seisData[0].toString()}`;
        }
        throw new Error(
          `first arg must be array of SeismogramDisplayData: ${msg}`
        );
      }
    } else {
      this._seisDataList = [];
    }
    if (isDef(seisConfig)) {
      this._seismographConfig = seisConfig;
    } else {
      this._seismographConfig = new SeismographConfig();
    }
    this._sorting = createDefaultSortingOptions();
    this.attachShadow({ mode: "open" });
  }
  get seisData() {
    return this._seisDataList;
  }
  set seisData(seisData) {
    this._seisDataList = [];
    this.appendSeisData(seisData);
  }
  removeAllSeisData() {
    this._seisDataList = [];
    this.seisDataUpdated();
  }
  /**
   * appends the seismogram(s) or SeismogramDisplayData as separate time series.
   *
   * @param seismogram data to append
   */
  appendSeisData(sddList) {
    if (!sddList) {
    } else if (Array.isArray(sddList)) {
      for (const s2 of sddList) {
        if (s2 instanceof SeismogramDisplayData) {
          this._seisDataList.push(s2);
        } else {
          this._seisDataList.push(SeismogramDisplayData.fromSeismogram(s2));
        }
      }
    } else {
      if (sddList instanceof SeismogramDisplayData) {
        this._seisDataList.push(sddList);
      } else {
        this._seisDataList.push(SeismogramDisplayData.fromSeismogram(sddList));
      }
    }
    this.seisDataUpdated();
  }
  get seismographConfig() {
    return this._seismographConfig;
  }
  set seismographConfig(seismographConfig) {
    this._seismographConfig = seismographConfig;
    this.seisDataUpdated();
  }
  setSeisDataAndConfig(seisData, seismographConfig) {
    this._seismographConfig = seismographConfig;
    this._seisDataList = [];
    this.appendSeisData(seisData);
  }
  /**
   * The sorting type to optionally sort the data by. New sort types may be
   * added by supplying a key and function that takes an SeismogramDisplayData
   * and returns a number, string or date. Sort of data is done using the
   * calculated value for each waveform. This is stored as an attribute on
   * the element, so changing the attribute has the same effect.
   * Default is SORT_NONE = "none".
   * @return sorting key
   */
  get sortby() {
    let k = this.hasAttribute(SORT_BY) ? this.getAttribute(SORT_BY) : SORT_NONE;
    if (!k) {
      k = SORT_NONE;
    }
    return k;
  }
  set sortby(val) {
    this.setAttribute(SORT_BY, val);
  }
  addSortingFunction(key, sddFunction) {
    this._sorting.set(key, sddFunction);
  }
  getSortingFunction(key) {
    const sortFun = this._sorting.get(key);
    if (sortFun) {
      return sortFun;
    }
    return createSortValueFunction(key);
  }
  /**
   * Sorts seisData by the this.sortby sorting type.
   * @return this.seisData sorted
   */
  sortedSeisData() {
    if (this.sortby === SORT_NONE) {
      return this.seisData;
    }
    return sortByFunction(this.seisData, this.getSortingFunction(this.sortby));
  }
  addStyle(css, id2) {
    return addStyleToElement(this, css, id2);
  }
  /**
   * Notification to the element that something about the current seismogram
   * data has changed. This could be that the actual waveform data has been updated
   * or that auxillary data like quake or channel has been added or that the
   * configuration has changed. This should trigger a redraw.
   */
  seisDataUpdated() {
    this.redraw();
  }
  connectedCallback() {
    this.redraw();
  }
  /**
   * Redraw the element. This implements a throttle so that many redraws
   * are coelsced into a single actual draw if they occur before the
   * next animation frame.
   */
  redraw() {
    if (this._throttleRedraw !== null) {
      cancelAnimationFrame(this._throttleRedraw);
    }
    this._throttleRedraw = requestAnimationFrame(() => {
      this.draw();
      this.onRedraw(this);
      this._throttleRedraw = null;
    });
  }
  /**
   * Draw the element, overridden by subclasses. Generally outside callers
   * should prefer calling redraw() as it handles throttling and calls the
   * onRedraw callback.
   */
  draw() {
    if (!this.isConnected) {
      return;
    }
  }
  getShadowRoot(autoAdd = true) {
    if (!this.shadowRoot) {
      if (autoAdd) {
        this.attachShadow({ mode: "open" });
        return this.getShadowRoot(false);
      } else {
        throw new Error("shadowRoot is missing");
      }
    } else {
      return this.shadowRoot;
    }
  }
  static get observedAttributes() {
    const mine = [
      SORT_BY
    ];
    return mine;
  }
};
function addStyleToElement(element, css, id2) {
  let shadowRoot = element.shadowRoot;
  if (!shadowRoot) {
    shadowRoot = element.attachShadow({ mode: "open" });
  }
  if (id2 != null) {
    const oldStyle = shadowRoot.querySelector(`#${id2}`);
    if (oldStyle != null) {
      shadowRoot.removeChild(oldStyle);
    }
  }
  const styleEl = document.createElement("style");
  styleEl.textContent = css;
  if (id2) {
    styleEl.setAttribute("id", id2);
  }
  const styleNodes = shadowRoot.querySelectorAll("style");
  const lastStyle = styleNodes[styleNodes.length - 1];
  if (lastStyle) {
    lastStyle.after(styleEl);
  } else {
    shadowRoot.insertBefore(styleEl, shadowRoot.firstChild);
  }
  return styleEl;
}

// node_modules/d3-dsv/src/dsv.js
var EOL = {};
var EOF = {};
var QUOTE = 34;
var NEWLINE = 10;
var RETURN = 13;
function objectConverter(columns) {
  return new Function("d", "return {" + columns.map(function(name, i) {
    return JSON.stringify(name) + ": d[" + i + '] || ""';
  }).join(",") + "}");
}
function customConverter(columns, f) {
  var object2 = objectConverter(columns);
  return function(row, i) {
    return f(object2(row), i, columns);
  };
}
function inferColumns(rows) {
  var columnSet = /* @__PURE__ */ Object.create(null), columns = [];
  rows.forEach(function(row) {
    for (var column in row) {
      if (!(column in columnSet)) {
        columns.push(columnSet[column] = column);
      }
    }
  });
  return columns;
}
function pad2(value, width) {
  var s2 = value + "", length = s2.length;
  return length < width ? new Array(width - length + 1).join(0) + s2 : s2;
}
function formatYear2(year) {
  return year < 0 ? "-" + pad2(-year, 6) : year > 9999 ? "+" + pad2(year, 6) : pad2(year, 4);
}
function formatDate(date6) {
  var hours = date6.getUTCHours(), minutes = date6.getUTCMinutes(), seconds2 = date6.getUTCSeconds(), milliseconds2 = date6.getUTCMilliseconds();
  return isNaN(date6) ? "Invalid Date" : formatYear2(date6.getUTCFullYear(), 4) + "-" + pad2(date6.getUTCMonth() + 1, 2) + "-" + pad2(date6.getUTCDate(), 2) + (milliseconds2 ? "T" + pad2(hours, 2) + ":" + pad2(minutes, 2) + ":" + pad2(seconds2, 2) + "." + pad2(milliseconds2, 3) + "Z" : seconds2 ? "T" + pad2(hours, 2) + ":" + pad2(minutes, 2) + ":" + pad2(seconds2, 2) + "Z" : minutes || hours ? "T" + pad2(hours, 2) + ":" + pad2(minutes, 2) + "Z" : "");
}
function dsv_default(delimiter) {
  var reFormat = new RegExp('["' + delimiter + "\n\r]"), DELIMITER = delimiter.charCodeAt(0);
  function parse5(text, f) {
    var convert2, columns, rows = parseRows(text, function(row, i) {
      if (convert2) return convert2(row, i - 1);
      columns = row, convert2 = f ? customConverter(row, f) : objectConverter(row);
    });
    rows.columns = columns || [];
    return rows;
  }
  function parseRows(text, f) {
    var rows = [], N = text.length, I = 0, n2 = 0, t, eof = N <= 0, eol = false;
    if (text.charCodeAt(N - 1) === NEWLINE) --N;
    if (text.charCodeAt(N - 1) === RETURN) --N;
    function token() {
      if (eof) return EOF;
      if (eol) return eol = false, EOL;
      var i, j = I, c;
      if (text.charCodeAt(j) === QUOTE) {
        while (I++ < N && text.charCodeAt(I) !== QUOTE || text.charCodeAt(++I) === QUOTE) ;
        if ((i = I) >= N) eof = true;
        else if ((c = text.charCodeAt(I++)) === NEWLINE) eol = true;
        else if (c === RETURN) {
          eol = true;
          if (text.charCodeAt(I) === NEWLINE) ++I;
        }
        return text.slice(j + 1, i - 1).replace(/""/g, '"');
      }
      while (I < N) {
        if ((c = text.charCodeAt(i = I++)) === NEWLINE) eol = true;
        else if (c === RETURN) {
          eol = true;
          if (text.charCodeAt(I) === NEWLINE) ++I;
        } else if (c !== DELIMITER) continue;
        return text.slice(j, i);
      }
      return eof = true, text.slice(j, N);
    }
    while ((t = token()) !== EOF) {
      var row = [];
      while (t !== EOL && t !== EOF) row.push(t), t = token();
      if (f && (row = f(row, n2++)) == null) continue;
      rows.push(row);
    }
    return rows;
  }
  function preformatBody(rows, columns) {
    return rows.map(function(row) {
      return columns.map(function(column) {
        return formatValue(row[column]);
      }).join(delimiter);
    });
  }
  function format2(rows, columns) {
    if (columns == null) columns = inferColumns(rows);
    return [columns.map(formatValue).join(delimiter)].concat(preformatBody(rows, columns)).join("\n");
  }
  function formatBody(rows, columns) {
    if (columns == null) columns = inferColumns(rows);
    return preformatBody(rows, columns).join("\n");
  }
  function formatRows(rows) {
    return rows.map(formatRow).join("\n");
  }
  function formatRow(row) {
    return row.map(formatValue).join(delimiter);
  }
  function formatValue(value) {
    return value == null ? "" : value instanceof Date ? formatDate(value) : reFormat.test(value += "") ? '"' + value.replace(/"/g, '""') + '"' : value;
  }
  return {
    parse: parse5,
    parseRows,
    format: format2,
    formatBody,
    formatRows,
    formatRow,
    formatValue
  };
}

// node_modules/d3-dsv/src/csv.js
var csv = dsv_default(",");
var csvParse = csv.parse;
var csvParseRows = csv.parseRows;
var csvFormat = csv.format;
var csvFormatBody = csv.formatBody;
var csvFormatRows = csv.formatRows;
var csvFormatRow = csv.formatRow;
var csvFormatValue = csv.formatValue;

// src/infotable.mts
var INFO_ELEMENT = "sp-station-quake-table";
var QUAKE_INFO_ELEMENT = "sp-quake-table";
var QUAKE_COLUMN = /* @__PURE__ */ ((QUAKE_COLUMN2) => {
  QUAKE_COLUMN2["LAT"] = "Lat";
  QUAKE_COLUMN2["LON"] = "Lon";
  QUAKE_COLUMN2["TIME"] = "Time";
  QUAKE_COLUMN2["LOCALTIME"] = "Local Time";
  QUAKE_COLUMN2["MAG"] = "Mag";
  QUAKE_COLUMN2["MAGTYPE"] = "MagType";
  QUAKE_COLUMN2["DEPTH"] = "Depth";
  QUAKE_COLUMN2["DESC"] = "Description";
  QUAKE_COLUMN2["EVENTID"] = "EventId";
  return QUAKE_COLUMN2;
})(QUAKE_COLUMN || {});
var CHANNEL_COLUMN = /* @__PURE__ */ ((CHANNEL_COLUMN2) => {
  CHANNEL_COLUMN2["LAT"] = "Lat";
  CHANNEL_COLUMN2["LON"] = "Lon";
  CHANNEL_COLUMN2["AZIMUTH"] = "Az";
  CHANNEL_COLUMN2["DIP"] = "Dip";
  CHANNEL_COLUMN2["START"] = "Start";
  CHANNEL_COLUMN2["END"] = "End";
  CHANNEL_COLUMN2["ELEVATION"] = "Elev";
  CHANNEL_COLUMN2["DEPTH"] = "Depth";
  CHANNEL_COLUMN2["SOURCEID"] = "SourceId";
  CHANNEL_COLUMN2["CODE"] = "Code";
  CHANNEL_COLUMN2["NETWORK_CODE"] = "NetworkCode";
  CHANNEL_COLUMN2["STATION_CODE"] = "StationCode";
  CHANNEL_COLUMN2["LOCATION_CODE"] = "LocationCode";
  CHANNEL_COLUMN2["CHANNEL_CODE"] = "ChannelCode";
  return CHANNEL_COLUMN2;
})(CHANNEL_COLUMN || {});
var STATION_COLUMN = /* @__PURE__ */ ((STATION_COLUMN2) => {
  STATION_COLUMN2["LAT"] = "Lat";
  STATION_COLUMN2["LON"] = "Lon";
  STATION_COLUMN2["START"] = "Start";
  STATION_COLUMN2["END"] = "End";
  STATION_COLUMN2["ELEVATION"] = "Elev";
  STATION_COLUMN2["SOURCEID"] = "SourceId";
  STATION_COLUMN2["CODE"] = "Code";
  STATION_COLUMN2["NETWORK_CODE"] = "NetworkCode";
  STATION_COLUMN2["STATION_CODE"] = "StationCode";
  STATION_COLUMN2["DESCRIPTION"] = "Description";
  return STATION_COLUMN2;
})(STATION_COLUMN || {});
var SEISMOGRAM_COLUMN = /* @__PURE__ */ ((SEISMOGRAM_COLUMN2) => {
  SEISMOGRAM_COLUMN2["START"] = "Start";
  SEISMOGRAM_COLUMN2["DURATION"] = "Duration";
  SEISMOGRAM_COLUMN2["END"] = "End";
  SEISMOGRAM_COLUMN2["NUM_POINTS"] = "Num Pts";
  SEISMOGRAM_COLUMN2["SAMPLE_RATE"] = "Sample Rate";
  SEISMOGRAM_COLUMN2["SAMPLE_PERIOD"] = "Sample Period";
  SEISMOGRAM_COLUMN2["SEGMENTS"] = "Segments";
  SEISMOGRAM_COLUMN2["SOURCEID"] = "SourceId";
  SEISMOGRAM_COLUMN2["CODE"] = "Codes";
  SEISMOGRAM_COLUMN2["NETWORK_CODE"] = "NetworkCode";
  SEISMOGRAM_COLUMN2["STATION_CODE"] = "StationCode";
  return SEISMOGRAM_COLUMN2;
})(SEISMOGRAM_COLUMN || {});
var DEFAULT_TEMPLATE = `
  <table>
  <thead>
      <tr>
        <th colspan="7">Waveform</th>
        <th colspan="4">Channel</th>
        <th colspan="6">Event</th>
        <th colspan="4">DistAz</th>
      </tr>
      <tr>
        <th>Codes</th>
        <th>Start</th>
        <th>Duration</th>
        <th>End</th>
        <th>Num Pts</th>
        <th>Sample Rate</th>
        <th>YUnit</th>
        <th>Seg</th>

        <th>Lat</th>
        <th>Lon</th>
        <th>Elev</th>
        <th>Depth</th>

        <th>Time</th>
        <th>Lat</th>
        <th>Lon</th>
        <th colspan="2">Mag</th>
        <th>Depth</th>

        <th>Dist deg</th>
        <th>Dist km</th>
        <th>Azimuth</th>
        <th>Back Azimuth</th>
      </tr>
    </thead>
    <tbody>
    {{#each seisDataList as |sdd|}}
      <tr>
        <td>{{sdd.nslc}}</td>
        <td>{{formatIsoDate sdd.seismogram.startTime}}</td>
        <td>{{formatDuration sdd.seismogram.timeRange}}</td>
        <td>{{formatIsoDate sdd.seismogram.endTime}}</td>
        <td>{{sdd.seismogram.numPoints}}</td>
        <td>{{sdd.seismogram.sampleRate}}</td>
        <td>{{sdd.seismogram.yUnit}}</td>
        <td>{{sdd.seismogram.segments.length}}</td>

        {{#if sdd.channel}}
          <td>{{sdd.channel.latitude}}</td>
          <td>{{sdd.channel.longitude}}</td>
          <td>{{sdd.channel.elevation}}</td>
          <td>{{sdd.channel.depth}}</td>
        {{else}}
          <td>no channel</td>
          <td/>
          <td/>
          <td/>
        {{/if}}

        {{#if sdd.quake }}
          <td>{{formatIsoDate sdd.quake.time}}</td>
          <td>{{sdd.quake.latitude}}</td>
          <td>{{sdd.quake.longitude}}</td>
          <td>{{sdd.quake.magnitude.mag}}</td>
          <td>{{sdd.quake.magnitude.type}}</td>
          <td>{{sdd.quake.depthKm}}</td>
        {{else}}
          <td>no quake</td>
          <td/>
          <td/>
          <td/>
          <td/>
          <td/>
        {{/if}}
        {{#if sdd.quake }}
          {{#if sdd.channel }}
            <td>{{formatNumber sdd.distaz.distanceDeg 2}}</td>
            <td>{{formatNumber sdd.distaz.distanceKm 0}}</td>
            <td>{{formatNumber sdd.distaz.az 2}}</td>
            <td>{{formatNumber sdd.distaz.baz 2}}</td>
          {{/if}}
        {{/if}}
      </tr>
    {{/each}}
    </tbody>
  </table>
`;
var TABLE_CSS = `
tbody tr:nth-child(even)
{
  background: var(--even-row-background, Cornsilk);
}
tbody tr:nth-child(odd)
{
  background: var(--odd-row-background);
}
table {
    display: block;
    overflow-x: auto;
    white-space: nowrap;
}
caption {
    caption-side: bottom;
}
`;
var QuakeStationTable = class extends SeisPlotElement {
  constructor(seisData, seisConfig) {
    super(seisData, seisConfig);
    this._template = DEFAULT_TEMPLATE;
    this.addStyle(TABLE_CSS);
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    this.getShadowRoot().appendChild(wrapper);
  }
  get template() {
    return this._template;
  }
  set template(t) {
    this._template = t;
    this.redraw();
  }
  draw() {
    if (!this.isConnected) {
      return;
    }
    const wrapper = this.getShadowRoot().querySelector("div");
    while (wrapper.firstChild) {
      if (wrapper.lastChild) {
        wrapper.removeChild(wrapper.lastChild);
      }
    }
    const handlebarsCompiled = import_handlebars.default.compile(this.template);
    wrapper.innerHTML = handlebarsCompiled(
      {
        seisDataList: this.seisData,
        seisConfig: this.seismographConfig
      },
      {
        allowProtoPropertiesByDefault: true
        // this might be a security issue???
      }
    );
  }
};
customElements.define(INFO_ELEMENT, QuakeStationTable);
var QuakeTable = class _QuakeTable extends HTMLElement {
  constructor(quakeList, columnLabels, columnValues) {
    super();
    this.lastSortAsc = true;
    if (!quakeList) {
      quakeList = [];
    }
    if (!columnLabels) {
      columnLabels = _QuakeTable.createDefaultColumnLabels();
    }
    if (!columnValues) {
      columnValues = /* @__PURE__ */ new Map();
      const defColumnValues = _QuakeTable.createDefaultColumnValues();
      for (const key of columnLabels.keys()) {
        if (defColumnValues.has(key)) {
          const fn = defColumnValues.get(key);
          if (fn != null) {
            columnValues.set(key, fn);
          } else {
            throw new Error(`QuakeTable function for key is missing: ${key}`);
          }
        } else {
          throw new Error(`Unknown QuakeTable key: ${key}`);
        }
      }
    }
    this._quakeList = quakeList;
    this._columnLabels = columnLabels;
    this._columnValues = columnValues;
    this._rowToQuake = /* @__PURE__ */ new Map();
    const shadow = this.attachShadow({ mode: "open" });
    const table = document.createElement("table");
    table.setAttribute("class", "wrapper");
    addStyleToElement(this, TABLE_CSS);
    shadow.appendChild(table);
  }
  get quakeList() {
    return this._quakeList;
  }
  set quakeList(ql) {
    this._quakeList = ql;
    this.draw();
  }
  get columnLabels() {
    return this._columnLabels;
  }
  set columnLabels(cols) {
    this._columnLabels = cols;
    this.draw();
  }
  get columnValues() {
    return this._columnValues;
  }
  set columnValues(cols) {
    this._columnValues = cols;
    this.draw();
  }
  get timeZone() {
    return this._timezone;
  }
  set timeZone(timezone) {
    this._timezone = timezone;
    this.draw();
  }
  get caption() {
    return this._caption;
  }
  set caption(cap) {
    this._caption = cap;
    const table = this.shadowRoot?.querySelector("table");
    if (table && this._caption) {
      const captionEl = table.createCaption();
      if (this._caption instanceof HTMLElement) {
        captionEl.innerHTML = "";
        captionEl.appendChild(this._caption);
      } else {
        captionEl.textContent = this._caption;
      }
    } else {
      table.deleteCaption();
    }
  }
  addColumn(key, label, valueFn) {
    this.columnLabels.set(key, label);
    this.columnValues.set(key, valueFn);
  }
  /**
   * Time format, passed to luxon toLocaleString()
   * https://moment.github.io/luxon/api-docs/index.html#datetimetolocalestring
   * @return time as a string
   */
  get timeFormat() {
    return this._timeFormat;
  }
  set timeFormat(timeFormat2) {
    this._timeFormat = timeFormat2;
    this.draw();
  }
  static createDefaultColumnLabels() {
    const columnLabels = /* @__PURE__ */ new Map();
    columnLabels.set("Time" /* TIME */, "Time");
    columnLabels.set("Lat" /* LAT */, "Lat");
    columnLabels.set("Lon" /* LON */, "Lon");
    columnLabels.set("Mag" /* MAG */, "Mag");
    columnLabels.set("MagType" /* MAGTYPE */, "Type");
    columnLabels.set("Depth" /* DEPTH */, "Depth");
    columnLabels.set("Description" /* DESC */, "Description");
    return columnLabels;
  }
  static createDefaultColumnValues() {
    const columnValues = /* @__PURE__ */ new Map();
    columnValues.set("Time" /* TIME */, (q) => stringify(q.time.toISO()));
    columnValues.set("Local Time" /* LOCALTIME */, (q) => stringify(q.time.setZone("local").toISO()));
    columnValues.set("Lat" /* LAT */, (q) => latlonFormat2.format(q.latitude));
    columnValues.set("Lon" /* LON */, (q) => latlonFormat2.format(q.longitude));
    columnValues.set("Mag" /* MAG */, (q) => magFormat2.format(q.magnitude.mag));
    columnValues.set("MagType" /* MAGTYPE */, (q) => q.magnitude.type ? q.magnitude.type : "");
    columnValues.set("Depth" /* DEPTH */, (q) => depthFormat2.format(q.depthKm));
    columnValues.set("EventId" /* EVENTID */, (q) => stringify(q.eventId));
    columnValues.set(
      "Description" /* DESC */,
      (q) => {
        const desc = q.description;
        if (desc && desc.length > 0) {
          return desc;
        } else {
          return stringify(q.time.toISO());
        }
      }
    );
    return columnValues;
  }
  addStyle(css, id2) {
    return addStyleToElement(this, css, id2);
  }
  findRowForQuake(q) {
    let quakeRow = null;
    this._rowToQuake.forEach((v, k) => {
      if (v === q) {
        quakeRow = k;
      }
    });
    return quakeRow;
  }
  draw() {
    if (!this.isConnected) {
      return;
    }
    const table = this.shadowRoot?.querySelector("table");
    if (this._caption) {
      const captionEl = table.createCaption();
      if (this._caption instanceof HTMLElement) {
        captionEl.innerHTML = "";
        captionEl.appendChild(this._caption);
      } else {
        captionEl.textContent = this._caption;
      }
    } else {
      table.deleteCaption();
    }
    table.deleteTHead();
    const theader = table.createTHead().insertRow();
    this.headers().forEach((h) => {
      const cell = theader.appendChild(document.createElement("th"));
      const label = this._columnLabels.has(h) ? this._columnLabels.get(h) : h;
      cell.textContent = `${label}`;
      if (h === "Local Time" /* LOCALTIME */) {
        if (this.timeZone) {
          cell.textContent = `${this._columnLabels.get(h)} ${nameForTimeZone(this.timeZone, DateTime.now())}`;
        } else {
          cell.textContent = `${this._columnLabels.get(h)} ${nameForTimeZone("local", DateTime.now())}`;
        }
      }
      cell.addEventListener("click", () => {
        this.sort(h, cell);
      });
    });
    table.querySelectorAll("tbody")?.forEach((tb) => {
      table.removeChild(tb);
    });
    const tbody = table.createTBody();
    this.quakeList.forEach((q) => {
      const row = tbody.insertRow();
      this.populateRow(q, row, -1);
      row.addEventListener("click", (evt) => {
        this.dispatchEvent(createQuakeClickEvent(q, evt));
      });
    });
  }
  headers() {
    return Array.from(this._columnValues.keys());
  }
  populateRow(q, row, index) {
    this._rowToQuake.set(row, q);
    this.headers().forEach((h) => {
      const cell = row.insertCell(index);
      if (h === "Local Time" /* LOCALTIME */ && this.timeZone) {
        const localQuakeTime = q.time.setZone(this.timeZone);
        if (this.timeFormat) {
          cell.textContent = localQuakeTime.toLocaleString(this.timeFormat);
        } else {
          cell.textContent = localQuakeTime.toISO();
        }
      } else {
        const cellValue = this.getQuakeValue(q, h);
        if (cellValue instanceof HTMLElement) {
          cell.appendChild(cellValue);
        } else {
          cell.textContent = cellValue;
        }
      }
      if (index !== -1) {
        index++;
      }
    });
  }
  tableToCSV() {
    const out = [];
    const headRow = [];
    out.push(headRow);
    this.headers().forEach((h) => {
      let label = this._columnLabels.has(h) ? this._columnLabels.get(h) : h;
      label = label ? label : "";
      headRow.push(label);
    });
    this._quakeList.forEach((q) => {
      const row = [];
      out.push(row);
      this.headers().forEach((h) => {
        const cellValue = this.getQuakeValue(q, h);
        if (cellValue instanceof HTMLElement) {
          row.push(cellValue.textContent);
        } else {
          row.push(cellValue);
        }
      });
    });
    return csvFormatRows(out);
  }
  getQuakeValue(q, h) {
    const fn = this._columnValues.has(h) ? this._columnValues.get(h) : null;
    if (fn != null) {
      return fn(q);
    } else {
      return `unknown: ${String(h)}`;
    }
  }
  sort(h, _headerCell) {
    const table = this.shadowRoot?.querySelector("table");
    const tbody = table.querySelector("tbody");
    if (tbody) {
      const rows = Array.from(tbody.querySelectorAll("tr"));
      rows.sort((rowa, rowb) => {
        let out = 0;
        const qa = this._rowToQuake.get(rowa);
        const qb = this._rowToQuake.get(rowb);
        if (qa && qb) {
          if (h === "Time" /* TIME */ || h === "Local Time" /* LOCALTIME */) {
            out = qa.time.toMillis() - qb.time.toMillis();
          } else if (h === "Lat" /* LAT */) {
            out = qa.latitude - qb.latitude;
          } else if (h === "Lon" /* LON */) {
            out = qa.longitude - qb.longitude;
          } else if (h === "Mag" /* MAG */) {
            out = qa.magnitude.mag - qb.magnitude.mag;
          } else if (h === "Depth" /* DEPTH */) {
            out = qa.depthKm - qb.depthKm;
          } else {
            const ta = this.getQuakeValue(qa, h);
            const tb = this.getQuakeValue(qb, h);
            if (ta < tb) {
              out = -1;
            } else if (ta > tb) {
              out = 1;
            } else {
              out = 0;
            }
          }
        } else {
        }
        return out;
      });
      if (this.lastSortCol === h) {
        if (this.lastSortAsc) {
          rows.reverse();
        }
        this.lastSortAsc = !this.lastSortAsc;
      } else {
        this.lastSortAsc = true;
      }
      rows.forEach((v) => {
        tbody.appendChild(v);
      });
      this.lastSortCol = h;
    } else {
    }
  }
};
customElements.define(QUAKE_INFO_ELEMENT, QuakeTable);
var ChannelTable = class _ChannelTable extends HTMLElement {
  constructor(channelList, columnLabels, columnValues) {
    super();
    this.lastSortAsc = true;
    if (!channelList) {
      channelList = [];
    }
    if (!columnLabels) {
      columnLabels = /* @__PURE__ */ new Map();
      columnLabels.set("Code" /* CODE */, "Code");
      columnLabels.set("Start" /* START */, "Start");
      columnLabels.set("End" /* END */, "End");
      columnLabels.set("Lat" /* LAT */, "Lat");
      columnLabels.set("Lon" /* LON */, "Lon");
      columnLabels.set("Az" /* AZIMUTH */, "Az");
      columnLabels.set("Dip" /* DIP */, "Dip");
      columnLabels.set("Depth" /* DEPTH */, "Depth");
      columnLabels.set("Elev" /* ELEVATION */, "Evel");
      columnLabels.set("SourceId" /* SOURCEID */, "SourceId");
    }
    this._channelList = channelList;
    this._columnLabels = columnLabels;
    this._rowToChannel = /* @__PURE__ */ new Map();
    if (!columnValues) {
      columnValues = /* @__PURE__ */ new Map();
      const defColumnValues = _ChannelTable.createDefaultColumnValues();
      for (const key of columnLabels.keys()) {
        if (defColumnValues.has(key)) {
          const fn = defColumnValues.get(key);
          if (fn != null) {
            columnValues.set(key, fn);
          } else {
            throw new Error(`ChannelTable function for key is missing: ${key}`);
          }
        } else {
          throw new Error(`Unknown ChannelTable key: ${key}`);
        }
      }
    }
    this._columnValues = columnValues;
    const shadow = this.attachShadow({ mode: "open" });
    const table = document.createElement("table");
    table.setAttribute("class", "wrapper");
    addStyleToElement(this, TABLE_CSS);
    shadow.appendChild(table);
  }
  get channelList() {
    return this._channelList;
  }
  set channelList(ql) {
    this._channelList = ql;
    this.draw();
  }
  get columnLabels() {
    return this._columnLabels;
  }
  set columnLabels(cols) {
    this._columnLabels = cols;
    this.draw();
  }
  get columnValues() {
    return this._columnValues;
  }
  set columnValues(cols) {
    this._columnValues = cols;
    this.draw();
  }
  addColumn(key, label, valueFn) {
    this.columnLabels.set(key, label);
    this.columnValues.set(key, valueFn);
  }
  get caption() {
    return this._caption;
  }
  set caption(cap) {
    this._caption = cap;
    const table = this.shadowRoot?.querySelector("table");
    if (table && this._caption) {
      const captionEl = table.createCaption();
      if (this._caption instanceof HTMLElement) {
        captionEl.innerHTML = "";
        captionEl.appendChild(this._caption);
      } else {
        captionEl.textContent = this._caption;
      }
    } else {
      table.deleteCaption();
    }
  }
  addStyle(css, id2) {
    return addStyleToElement(this, css, id2);
  }
  draw() {
    if (!this.isConnected) {
      return;
    }
    const table = this.shadowRoot?.querySelector("table");
    if (this._caption) {
      const captionEl = table.createCaption();
      if (this._caption instanceof HTMLElement) {
        captionEl.innerHTML = "";
        captionEl.appendChild(this._caption);
      } else {
        captionEl.textContent = this._caption;
      }
    } else {
      table.deleteCaption();
    }
    table.deleteTHead();
    const theader = table.createTHead().insertRow();
    this.headers().forEach((h) => {
      const cell = theader.appendChild(document.createElement("th"));
      const label = this._columnLabels.has(h) ? this._columnLabels.get(h) : h;
      cell.textContent = `${label}`;
      cell.addEventListener("click", () => {
        this.sort(h, cell);
      });
    });
    table.querySelectorAll("tbody")?.forEach((tb) => {
      table.removeChild(tb);
    });
    const tbody = table.createTBody();
    this.channelList.forEach((c) => {
      const row = tbody.insertRow();
      this.populateRow(c, row, -1);
      row.addEventListener("click", (evt) => {
        this.dispatchEvent(createChannelClickEvent(c, evt));
      });
    });
  }
  headers() {
    return Array.from(this._columnLabels.keys());
  }
  populateRow(q, row, index) {
    this._rowToChannel.set(row, q);
    this.headers().forEach((h) => {
      const cell = row.insertCell(index);
      const cellValue = this.getChannelValue(q, h);
      if (cellValue instanceof HTMLElement) {
        cell.appendChild(cellValue);
      } else {
        cell.textContent = cellValue;
      }
      if (index !== -1) {
        index++;
      }
    });
  }
  tableToCSV() {
    const out = [];
    const headRow = [];
    out.push(headRow);
    this.headers().forEach((h) => {
      let label = this._columnLabels.has(h) ? this._columnLabels.get(h) : h;
      label = label ? label : "";
      headRow.push(label);
    });
    this._channelList.forEach((q) => {
      const row = [];
      out.push(row);
      this.headers().forEach((h) => {
        const cellValue = this.getChannelValue(q, h);
        if (cellValue instanceof HTMLElement) {
          row.push(cellValue.textContent);
        } else {
          row.push(cellValue);
        }
      });
    });
    return csvFormatRows(out);
  }
  getChannelValue(c, h) {
    const fn = this._columnValues.has(h) ? this._columnValues.get(h) : null;
    if (fn != null) {
      return fn(c);
    } else {
      return `unknown: ${String(h)}`;
    }
  }
  static createDefaultColumnValues() {
    const columnValues = /* @__PURE__ */ new Map();
    columnValues.set("Start" /* START */, (c) => stringify(c.startDate.toISO()));
    columnValues.set("End" /* END */, (c) => c.endDate ? stringify(c.endDate.toISO()) : "");
    columnValues.set("Lat" /* LAT */, (c) => latlonFormat2.format(c.latitude));
    columnValues.set("Lon" /* LON */, (c) => latlonFormat2.format(c.longitude));
    columnValues.set("Elev" /* ELEVATION */, (c) => depthMeterFormat2.format(c.elevation));
    columnValues.set("Depth" /* DEPTH */, (c) => depthFormat2.format(c.depth));
    columnValues.set("Az" /* AZIMUTH */, (c) => latlonFormat2.format(c.azimuth));
    columnValues.set("Dip" /* DIP */, (c) => latlonFormat2.format(c.dip));
    columnValues.set("SourceId" /* SOURCEID */, (c) => stringify(c.sourceId.toString()));
    columnValues.set("Code" /* CODE */, (c) => stringify(c.codes()));
    columnValues.set("NetworkCode" /* NETWORK_CODE */, (c) => c.networkCode);
    columnValues.set("StationCode" /* STATION_CODE */, (c) => c.stationCode);
    columnValues.set("LocationCode" /* LOCATION_CODE */, (c) => c.locationCode);
    columnValues.set("ChannelCode" /* CHANNEL_CODE */, (c) => c.channelCode);
    columnValues.set("Code" /* CODE */, (c) => stringify(c.codes()));
    return columnValues;
  }
  static getChannelValue(q, h) {
    if (h === "Start" /* START */) {
      return stringify(q.startDate.toISO());
    } else if (h === "End" /* END */) {
      return q.endDate ? stringify(q.endDate.toISO()) : "";
    } else if (h === "Lat" /* LAT */) {
      return latlonFormat2.format(q.latitude);
    } else if (h === "Lon" /* LON */) {
      return latlonFormat2.format(q.longitude);
    } else if (h === "Elev" /* ELEVATION */) {
      return depthMeterFormat2.format(q.elevation);
    } else if (h === "Depth" /* DEPTH */) {
      return depthMeterFormat2.format(q.depth);
    } else if (h === "Az" /* AZIMUTH */) {
      return latlonFormat2.format(q.azimuth);
    } else if (h === "Dip" /* DIP */) {
      return latlonFormat2.format(q.dip);
    } else if (h === "SourceId" /* SOURCEID */) {
      return `${q.sourceId.toString()}`;
    } else if (h === "Code" /* CODE */) {
      return `${q.codes()}`;
    } else if (h === "NetworkCode" /* NETWORK_CODE */) {
      return `${q.networkCode}`;
    } else if (h === "StationCode" /* STATION_CODE */) {
      return `${q.stationCode}`;
    } else if (h === "LocationCode" /* LOCATION_CODE */) {
      return `${q.locationCode}`;
    } else if (h === "ChannelCode" /* CHANNEL_CODE */) {
      return `${q.channelCode}`;
    } else {
      return `unknown: ${String(h)}`;
    }
  }
  sort(h, _headerCell) {
    const table = this.shadowRoot?.querySelector("table");
    const tbody = table.querySelector("tbody");
    if (tbody) {
      const rows = Array.from(tbody.querySelectorAll("tr"));
      rows.sort((rowa, rowb) => {
        let out = 0;
        const qa = this._rowToChannel.get(rowa);
        const qb = this._rowToChannel.get(rowb);
        if (qa && qb) {
          if (h === "Start" /* START */) {
            out = qa.startDate.toMillis() - qb.startDate.toMillis();
          } else if (h === "End" /* END */) {
            if (qa.endDate && qb.endDate) {
              out = qa.endDate.toMillis() - qb.endDate.toMillis();
            } else if (qb.endDate) {
              return 1;
            } else {
              return -1;
            }
          } else if (h === "Lat" /* LAT */) {
            out = qa.latitude - qb.latitude;
          } else if (h === "Lon" /* LON */) {
            out = qa.longitude - qb.longitude;
          } else if (h === "Az" /* AZIMUTH */) {
            out = qa.azimuth - qb.azimuth;
          } else if (h === "Dip" /* DIP */) {
            out = qa.dip - qb.dip;
          } else if (h === "Depth" /* DEPTH */) {
            out = qa.depth - qb.depth;
          } else if (h === "Elev" /* ELEVATION */) {
            out = qa.elevation - qb.elevation;
          } else {
            const ta = this.getChannelValue(qa, h);
            const tb = this.getChannelValue(qb, h);
            if (ta < tb) {
              out = -1;
            } else if (ta > tb) {
              out = 1;
            } else {
              out = 0;
            }
          }
        } else {
        }
        return out;
      });
      if (this.lastSortCol === h) {
        if (this.lastSortAsc) {
          rows.reverse();
        }
        this.lastSortAsc = !this.lastSortAsc;
      } else {
        this.lastSortAsc = true;
      }
      rows.forEach((v) => {
        tbody.appendChild(v);
      });
      this.lastSortCol = h;
    } else {
    }
  }
};
var CHANNEL_INFO_ELEMENT = "sp-channel-table";
customElements.define(CHANNEL_INFO_ELEMENT, ChannelTable);
var StationTable = class _StationTable extends HTMLElement {
  constructor(stationList, columnLabels, columnValues) {
    super();
    this._columnLabels = /* @__PURE__ */ new Map();
    this.lastSortAsc = true;
    if (!stationList) {
      stationList = [];
    }
    if (!columnLabels) {
      columnLabels = _StationTable.createDefaultColumnLabels();
    }
    this._columnLabels = columnLabels;
    if (!columnValues) {
      columnValues = /* @__PURE__ */ new Map();
      const defColumnValues = _StationTable.createDefaultColumnValues();
      for (const key of columnLabels.keys()) {
        if (defColumnValues.has(key)) {
          const fn = defColumnValues.get(key);
          if (fn != null) {
            columnValues.set(key, fn);
          } else {
            throw new Error(`StationTable function for key is missing: ${key}`);
          }
        } else {
          throw new Error(`Unknown StationTable key: ${key}`);
        }
      }
    }
    this._columnValues = columnValues;
    this._stationList = stationList;
    this._rowToStation = /* @__PURE__ */ new Map();
    const shadow = this.attachShadow({ mode: "open" });
    const table = document.createElement("table");
    table.setAttribute("class", "wrapper");
    addStyleToElement(this, TABLE_CSS);
    shadow.appendChild(table);
  }
  get stationList() {
    return this._stationList;
  }
  set stationList(ql) {
    this._stationList = ql;
    this.draw();
  }
  get columnLabels() {
    return this._columnLabels;
  }
  set columnLabels(cols) {
    this._columnLabels = cols;
    this.draw();
  }
  get columnValues() {
    return this._columnValues;
  }
  set columnValues(cols) {
    this._columnValues = cols;
    this.draw();
  }
  addColumn(key, label, valueFn) {
    this.columnLabels.set(key, label);
    this.columnValues.set(key, valueFn);
  }
  get caption() {
    return this._caption;
  }
  set caption(cap) {
    this._caption = cap;
    const table = this.shadowRoot?.querySelector("table");
    if (table && this._caption) {
      const captionEl = table.createCaption();
      if (this._caption instanceof HTMLElement) {
        captionEl.innerHTML = "";
        captionEl.appendChild(this._caption);
      } else {
        captionEl.textContent = this._caption;
      }
    } else {
      table.deleteCaption();
    }
  }
  addStyle(css, id2) {
    return addStyleToElement(this, css, id2);
  }
  draw() {
    if (!this.isConnected) {
      return;
    }
    const table = this.shadowRoot?.querySelector("table");
    if (this._caption) {
      const captionEl = table.createCaption();
      if (this._caption instanceof HTMLElement) {
        captionEl.innerHTML = "";
        captionEl.appendChild(this._caption);
      } else {
        captionEl.textContent = this._caption;
      }
    } else {
      table.deleteCaption();
    }
    table.deleteTHead();
    const theader = table.createTHead().insertRow();
    this.headers().forEach((h) => {
      const cell = theader.appendChild(document.createElement("th"));
      const label = this._columnLabels.has(h) ? this._columnLabels.get(h) : h;
      cell.textContent = `${label}`;
      cell.addEventListener("click", () => {
        this.sort(h, cell);
      });
    });
    table.querySelectorAll("tbody")?.forEach((tb) => {
      table.removeChild(tb);
    });
    const tbody = table.createTBody();
    this.stationList.forEach((s2) => {
      const row = tbody.insertRow();
      this.populateRow(s2, row, -1);
      row.addEventListener("click", (evt) => {
        this.dispatchEvent(createStationClickEvent(s2, evt));
      });
    });
  }
  headers() {
    return Array.from(this._columnValues.keys());
  }
  populateRow(q, row, index) {
    this._rowToStation.set(row, q);
    this.headers().forEach((h) => {
      const cell = row.insertCell(index);
      const cellValue = this.getStationValue(q, h);
      if (cellValue instanceof HTMLElement) {
        cell.appendChild(cellValue);
      } else {
        cell.textContent = cellValue;
      }
      if (index !== -1) {
        index++;
      }
    });
  }
  tableToCSV() {
    const out = [];
    const headRow = [];
    out.push(headRow);
    this.headers().forEach((h) => {
      let label = this._columnLabels.has(h) ? this._columnLabels.get(h) : h;
      label = label ? label : "";
      headRow.push(label);
    });
    this._stationList.forEach((q) => {
      const row = [];
      out.push(row);
      this.headers().forEach((h) => {
        const cellValue = this.getStationValue(q, h);
        if (cellValue instanceof HTMLElement) {
          row.push(cellValue.textContent);
        } else {
          row.push(cellValue);
        }
      });
    });
    return csvFormatRows(out);
  }
  static createDefaultColumnLabels() {
    const columnLabels = /* @__PURE__ */ new Map();
    columnLabels.set("Code" /* CODE */, "Code");
    columnLabels.set("Start" /* START */, "Start");
    columnLabels.set("End" /* END */, "End");
    columnLabels.set("Lat" /* LAT */, "Lat");
    columnLabels.set("Lon" /* LON */, "Lon");
    columnLabels.set("Elev" /* ELEVATION */, "Evel");
    columnLabels.set("SourceId" /* SOURCEID */, "SourceId");
    return columnLabels;
  }
  static createDefaultColumnValues() {
    const columnValues = /* @__PURE__ */ new Map();
    columnValues.set("Start" /* START */, (sta) => stringify(sta.startDate.toISO()));
    columnValues.set("End" /* END */, (sta) => sta.endDate ? stringify(sta.endDate.toISO()) : "");
    columnValues.set("Lat" /* LAT */, (sta) => latlonFormat2.format(sta.latitude));
    columnValues.set("Lon" /* LON */, (sta) => latlonFormat2.format(sta.longitude));
    columnValues.set("Elev" /* ELEVATION */, (sta) => depthMeterFormat2.format(sta.elevation));
    columnValues.set("SourceId" /* SOURCEID */, (sta) => `${sta.sourceId.toString()}`);
    columnValues.set("Code" /* CODE */, (sta) => `${sta.codes()}`);
    columnValues.set("NetworkCode" /* NETWORK_CODE */, (sta) => `${sta.networkCode}`);
    columnValues.set("StationCode" /* STATION_CODE */, (sta) => `${sta.stationCode}`);
    columnValues.set("Description" /* DESCRIPTION */, (sta) => `${sta.description}`);
    return columnValues;
  }
  getStationValue(q, h) {
    if (this._columnValues.has(h)) {
      const fn = this._columnValues.get(h);
      if (fn != null) {
        return fn(q);
      }
    }
    if (h === "Start" /* START */) {
      return stringify(q.startDate.toISO());
    } else if (h === "End" /* END */) {
      return q.endDate ? stringify(q.endDate.toISO()) : "";
    } else if (h === "Lat" /* LAT */) {
      return latlonFormat2.format(q.latitude);
    } else if (h === "Lon" /* LON */) {
      return latlonFormat2.format(q.longitude);
    } else if (h === "Elev" /* ELEVATION */) {
      return depthMeterFormat2.format(q.elevation);
    } else if (h === "SourceId" /* SOURCEID */) {
      return `${q.sourceId.toString()}`;
    } else if (h === "Code" /* CODE */) {
      return `${q.codes()}`;
    } else if (h === "NetworkCode" /* NETWORK_CODE */) {
      return `${q.networkCode}`;
    } else if (h === "StationCode" /* STATION_CODE */) {
      return `${q.stationCode}`;
    } else if (h === "Description" /* DESCRIPTION */) {
      return `${q.description}`;
    } else {
      return `unknown: ${String(h)}`;
    }
  }
  sort(h, _headerCell) {
    const table = this.shadowRoot?.querySelector("table");
    const tbody = table.querySelector("tbody");
    if (tbody) {
      const rows = Array.from(tbody.querySelectorAll("tr"));
      rows.sort((rowa, rowb) => {
        let out = 0;
        const qa = this._rowToStation.get(rowa);
        const qb = this._rowToStation.get(rowb);
        if (qa && qb) {
          if (h === "Start" /* START */) {
            out = qa.startDate.toMillis() - qb.startDate.toMillis();
          } else if (h === "End" /* END */) {
            if (qa.endDate && qb.endDate) {
              out = qa.endDate.toMillis() - qb.endDate.toMillis();
            } else if (qb.endDate) {
              return 1;
            } else {
              return -1;
            }
          } else if (h === "Lat" /* LAT */) {
            out = qa.latitude - qb.latitude;
          } else if (h === "Lon" /* LON */) {
            out = qa.longitude - qb.longitude;
          } else if (h === "Elev" /* ELEVATION */) {
            out = qa.elevation - qb.elevation;
          } else {
            const ta = this.getStationValue(qa, h);
            const tb = this.getStationValue(qb, h);
            if (ta < tb) {
              out = -1;
            } else if (ta > tb) {
              out = 1;
            } else {
              out = 0;
            }
          }
        } else {
        }
        return out;
      });
      if (this.lastSortCol === h) {
        if (this.lastSortAsc) {
          rows.reverse();
        }
        this.lastSortAsc = !this.lastSortAsc;
      } else {
        this.lastSortAsc = true;
      }
      rows.forEach((v) => {
        tbody.appendChild(v);
      });
      this.lastSortCol = h;
    } else {
    }
  }
};
var STATION_INFO_ELEMENT = "sp-station-table";
customElements.define(STATION_INFO_ELEMENT, StationTable);
var SeismogramTable = class _SeismogramTable extends HTMLElement {
  constructor(sddList, columnLabels, columnValues) {
    super();
    this.lastSortAsc = true;
    if (!sddList) {
      sddList = [];
    }
    if (!columnLabels) {
      columnLabels = /* @__PURE__ */ new Map();
      columnLabels.set("Codes" /* CODE */, "Code");
      columnLabels.set("Start" /* START */, "Start");
      columnLabels.set("End" /* END */, "End");
      columnLabels.set("Duration" /* DURATION */, "Dur");
      columnLabels.set("Sample Rate" /* SAMPLE_RATE */, "Sample Rate");
      columnLabels.set("Sample Period" /* SAMPLE_PERIOD */, "Sample Period");
      columnLabels.set("Num Pts" /* NUM_POINTS */, "Npts");
      columnLabels.set("Segments" /* SEGMENTS */, "Segments");
      columnLabels.set("SourceId" /* SOURCEID */, "SourceId");
    }
    this._sddList = sddList;
    this._columnLabels = columnLabels;
    this._rowToSDD = /* @__PURE__ */ new Map();
    if (!columnValues) {
      columnValues = /* @__PURE__ */ new Map();
      const defColumnValues = _SeismogramTable.createDefaultColumnValues();
      for (const key of columnLabels.keys()) {
        if (defColumnValues.has(key)) {
          const fn = defColumnValues.get(key);
          if (fn != null) {
            columnValues.set(key, fn);
          } else {
            throw new Error(`SeismogramTable function for key is missing: ${key}`);
          }
        } else {
          throw new Error(`Unknown SeismogramTable key: ${key}`);
        }
      }
    }
    this._columnValues = columnValues;
    const shadow = this.attachShadow({ mode: "open" });
    const table = document.createElement("table");
    table.setAttribute("class", "wrapper");
    addStyleToElement(this, TABLE_CSS);
    shadow.appendChild(table);
  }
  get seisData() {
    return this._sddList;
  }
  set seisData(ql) {
    this._sddList = ql;
    this.draw();
  }
  get columnLabels() {
    return this._columnLabels;
  }
  set columnLabels(cols) {
    this._columnLabels = cols;
    this.draw();
  }
  get columnValues() {
    return this._columnValues;
  }
  set columnValues(cols) {
    this._columnValues = cols;
    this.draw();
  }
  addColumn(key, label, valueFn) {
    this.columnLabels.set(key, label);
    this.columnValues.set(key, valueFn);
  }
  get caption() {
    return this._caption;
  }
  set caption(cap) {
    this._caption = cap;
    const table = this.shadowRoot?.querySelector("table");
    if (table && this._caption) {
      const captionEl = table.createCaption();
      if (this._caption instanceof HTMLElement) {
        captionEl.innerHTML = "";
        captionEl.appendChild(this._caption);
      } else {
        captionEl.textContent = this._caption;
      }
    } else {
      table.deleteCaption();
    }
  }
  addStyle(css, id2) {
    return addStyleToElement(this, css, id2);
  }
  draw() {
    if (!this.isConnected) {
      return;
    }
    const table = this.shadowRoot?.querySelector("table");
    if (this._caption) {
      const captionEl = table.createCaption();
      if (this._caption instanceof HTMLElement) {
        captionEl.innerHTML = "";
        captionEl.appendChild(this._caption);
      } else {
        captionEl.textContent = this._caption;
      }
    } else {
      table.deleteCaption();
    }
    table.deleteTHead();
    const theader = table.createTHead().insertRow();
    this.headers().forEach((h) => {
      const cell = theader.appendChild(document.createElement("th"));
      const label = this._columnLabels.has(h) ? this._columnLabels.get(h) : h;
      cell.textContent = `${label}`;
      cell.addEventListener("click", () => {
        this.sort(h, cell);
      });
    });
    table.querySelectorAll("tbody")?.forEach((tb) => {
      table.removeChild(tb);
    });
    const tbody = table.createTBody();
    this._sddList.forEach((q) => {
      const row = tbody.insertRow();
      this.populateRow(q, row, -1);
    });
  }
  headers() {
    return Array.from(this._columnLabels.keys());
  }
  populateRow(q, row, index) {
    this._rowToSDD.set(row, q);
    this.headers().forEach((h) => {
      const cell = row.insertCell(index);
      const cellValue = this.getSeismogramValue(q, h);
      if (cellValue instanceof HTMLElement) {
        cell.appendChild(cellValue);
      } else {
        cell.textContent = cellValue;
      }
      if (index !== -1) {
        index++;
      }
    });
  }
  tableToCSV() {
    const out = [];
    const headRow = [];
    out.push(headRow);
    this.headers().forEach((h) => {
      let label = this._columnLabels.has(h) ? this._columnLabels.get(h) : h;
      label = label ? label : "";
      headRow.push(label);
    });
    this._sddList.forEach((q) => {
      const row = [];
      out.push(row);
      this.headers().forEach((h) => {
        const cellValue = this.getSeismogramValue(q, h);
        if (cellValue instanceof HTMLElement) {
          row.push(cellValue.textContent);
        } else {
          row.push(cellValue);
        }
      });
    });
    return csvFormatRows(out);
  }
  getSeismogramValue(q, h) {
    const fn = this._columnValues.has(h) ? this._columnValues.get(h) : null;
    if (fn != null) {
      return fn(q);
    } else {
      return `unknown: ${String(h)}`;
    }
  }
  static createDefaultColumnValues() {
    const columnValues = /* @__PURE__ */ new Map();
    columnValues.set("Start" /* START */, (q) => stringify(q.start.toISO()));
    columnValues.set("End" /* END */, (q) => stringify(q.start.toISO()));
    columnValues.set("Duration" /* DURATION */, (q) => stringify(q.timeRange.toDuration().toISO()));
    columnValues.set("Num Pts" /* NUM_POINTS */, (q) => `${q.numPoints}`);
    columnValues.set("Sample Rate" /* SAMPLE_RATE */, (q) => `${q._seismogram?.sampleRate}`);
    columnValues.set("Sample Period" /* SAMPLE_PERIOD */, (q) => `${q._seismogram?.samplePeriod}`);
    columnValues.set("Segments" /* SEGMENTS */, (q) => `${q._seismogram?.segments.length}`);
    columnValues.set("SourceId" /* SOURCEID */, (q) => `${q.sourceId.toString()}`);
    columnValues.set("Codes" /* CODE */, (q) => `${q.codes()}`);
    columnValues.set("NetworkCode" /* NETWORK_CODE */, (q) => `${q.networkCode}`);
    columnValues.set("StationCode" /* STATION_CODE */, (q) => `${q.stationCode}`);
    return columnValues;
  }
  static getSeismogramValue(q, h) {
    if (h === "Start" /* START */) {
      return stringify(q.start.toISO());
    } else if (h === "End" /* END */) {
      return stringify(q.end.toISO());
    } else if (h === "Duration" /* DURATION */) {
      return stringify(q.timeRange.toDuration().toISO());
    } else if (h === "Num Pts" /* NUM_POINTS */) {
      return `${q.numPoints}`;
    } else if (h === "Sample Rate" /* SAMPLE_RATE */) {
      return q._seismogram ? `${q._seismogram.sampleRate}` : "";
    } else if (h === "Sample Period" /* SAMPLE_PERIOD */) {
      return q._seismogram ? `${q._seismogram.samplePeriod}` : "";
    } else if (h === "Segments" /* SEGMENTS */) {
      return q._seismogram ? `${q._seismogram.segments.length}` : "";
    } else if (h === "SourceId" /* SOURCEID */) {
      return `${q.sourceId.toString()}`;
    } else if (h === "Codes" /* CODE */) {
      return `${q.codes()}`;
    } else if (h === "NetworkCode" /* NETWORK_CODE */) {
      return `${q.networkCode}`;
    } else if (h === "StationCode" /* STATION_CODE */) {
      return `${q.stationCode}`;
    } else {
      return `unknown: ${String(h)}`;
    }
  }
  sort(h, _headerCell) {
    const table = this.shadowRoot?.querySelector("table");
    const tbody = table.querySelector("tbody");
    if (tbody) {
      const rows = Array.from(tbody.querySelectorAll("tr"));
      rows.sort((rowa, rowb) => {
        let out = 0;
        const qa = this._rowToSDD.get(rowa);
        const qb = this._rowToSDD.get(rowb);
        if (qa && qb) {
          if (h === "Start" /* START */) {
            out = qa.start.toMillis() - qb.start.toMillis();
          } else if (h === "End" /* END */) {
            out = qa.end.toMillis() - qb.end.toMillis();
          } else if (h === "Duration" /* DURATION */) {
            out = qa.timeRange.toDuration().toMillis() - qb.timeRange.toDuration().toMillis();
          } else if (h === "Num Pts" /* NUM_POINTS */) {
            out = qa.numPoints - qb.numPoints;
          } else if (h === "Sample Rate" /* SAMPLE_RATE */) {
            out = (qa._seismogram ? qa._seismogram.sampleRate : 0) - (qb._seismogram ? qb._seismogram.sampleRate : 0);
          } else if (h === "Sample Period" /* SAMPLE_PERIOD */) {
            out = (qa._seismogram ? qa._seismogram.samplePeriod : 0) - (qb._seismogram ? qb._seismogram.samplePeriod : 0);
          } else if (h === "Segments" /* SEGMENTS */) {
            out = (qa._seismogram ? qa._seismogram.segments.length : 0) - (qb._seismogram ? qb._seismogram.segments.length : 0);
          } else {
            const ta = _SeismogramTable.getSeismogramValue(qa, h);
            const tb = _SeismogramTable.getSeismogramValue(qb, h);
            if (ta < tb) {
              out = -1;
            } else if (ta > tb) {
              out = 1;
            } else {
              out = 0;
            }
          }
        } else {
        }
        return out;
      });
      if (this.lastSortCol === h) {
        if (this.lastSortAsc) {
          rows.reverse();
        }
        this.lastSortAsc = !this.lastSortAsc;
      } else {
        this.lastSortAsc = true;
      }
      rows.forEach((v) => {
        tbody.appendChild(v);
      });
      this.lastSortCol = h;
    } else {
    }
  }
};
var SDD_INFO_ELEMENT = "sp-seismogram-table";
customElements.define(SDD_INFO_ELEMENT, SeismogramTable);
var latlonFormat2 = latlonFormat;
var magFormat2 = magFormat;
var depthFormat2 = depthFormat;
var depthNoUnitFormat2 = depthNoUnitFormat;
var depthMeterFormat2 = depthMeterFormat;

// src/leafletutil.mts
var leafletutil_exports = {};
__export(leafletutil_exports, {
  CENTER_LAT: () => CENTER_LAT,
  CENTER_LON: () => CENTER_LON,
  CIRCLE: () => CIRCLE,
  CROSS: () => CROSS,
  DEFAULT_CENTER_LAT: () => DEFAULT_CENTER_LAT,
  DEFAULT_CENTER_LON: () => DEFAULT_CENTER_LON,
  DEFAULT_MAG_SCALE: () => DEFAULT_MAG_SCALE,
  DEFAULT_MAX_ZOOM: () => DEFAULT_MAX_ZOOM,
  DEFAULT_TILE_TEMPLATE: () => DEFAULT_TILE_TEMPLATE,
  DEFAULT_ZOOM_LEVEL: () => DEFAULT_ZOOM_LEVEL,
  DOWNTRIANGLE: () => DOWNTRIANGLE,
  FIT_BOUNDS: () => FIT_BOUNDS,
  HIGHLIGHT: () => HIGHLIGHT,
  InactiveStationMarkerClassName: () => InactiveStationMarkerClassName,
  LEAFLET_CSS_ID: () => LEAFLET_CSS_ID,
  MAG_SCALE: () => MAG_SCALE,
  MAP_CSS_ID: () => MAP_CSS_ID,
  MAP_ELEMENT: () => MAP_ELEMENT,
  MARKER_CSS_ID: () => MARKER_CSS_ID,
  MAX_ZOOM: () => MAX_ZOOM,
  QUAKE_MARKER_STYLE_EL: () => QUAKE_MARKER_STYLE_EL,
  QuakeMarkerClassName: () => QuakeMarkerClassName,
  QuakeStationMap: () => QuakeStationMap,
  SQUARE: () => SQUARE,
  STATION_CODE_SEP: () => STATION_CODE_SEP,
  STATION_ICON_SIZE: () => STATION_ICON_SIZE,
  STATION_MARKER_STYLE_EL: () => STATION_MARKER_STYLE_EL,
  StationMarkerClassName: () => StationMarkerClassName,
  TILE_ATTRIBUTION: () => TILE_ATTRIBUTION,
  TILE_TEMPLATE: () => TILE_TEMPLATE,
  TRIANGLE: () => TRIANGLE,
  UNSELECTED: () => UNSELECTED,
  ZOOM_LEVEL: () => ZOOM_LEVEL,
  createQuakeMarker: () => createQuakeMarker,
  createStationMarker: () => createStationMarker,
  createStationSVG: () => createStationSVG,
  cssClassForNetworkCode: () => cssClassForNetworkCode,
  cssClassForQuake: () => cssClassForQuake,
  cssClassForStationCodes: () => cssClassForStationCodes,
  defaultMapElement_css: () => defaultMapElement_css,
  defaultMarker_css: () => defaultMarker_css,
  getRadiusForMag: () => getRadiusForMag,
  inactiveStationIcon: () => inactiveStationIcon,
  leaflet_css: () => leaflet_css2,
  stationIcon: () => stationIcon,
  stationMarker_css: () => stationMarker_css
});

// src/leaflet_css.mts
var leaflet_css = `
/* required styles */

.leaflet-pane,
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-tile-container,
.leaflet-pane > svg,
.leaflet-pane > canvas,
.leaflet-zoom-box,
.leaflet-image-layer,
.leaflet-layer {
	position: absolute;
	left: 0;
	top: 0;
	}
.leaflet-container {
	overflow: hidden;
	}
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow {
	-webkit-user-select: none;
	   -moz-user-select: none;
	        user-select: none;
	  -webkit-user-drag: none;
	}
/* Prevents IE11 from highlighting tiles in blue */
.leaflet-tile::selection {
	background: transparent;
}
/* Safari renders non-retina tile on retina better with this, but Chrome is worse */
.leaflet-safari .leaflet-tile {
	image-rendering: -webkit-optimize-contrast;
	}
/* hack that prevents hw layers "stretching" when loading new tiles */
.leaflet-safari .leaflet-tile-container {
	width: 1600px;
	height: 1600px;
	-webkit-transform-origin: 0 0;
	}
.leaflet-marker-icon,
.leaflet-marker-shadow {
	display: block;
	}
/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */
/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */
.leaflet-container .leaflet-overlay-pane svg {
	max-width: none !important;
	max-height: none !important;
	}
.leaflet-container .leaflet-marker-pane img,
.leaflet-container .leaflet-shadow-pane img,
.leaflet-container .leaflet-tile-pane img,
.leaflet-container img.leaflet-image-layer,
.leaflet-container .leaflet-tile {
	max-width: none !important;
	max-height: none !important;
	width: auto;
	padding: 0;
	}

.leaflet-container img.leaflet-tile {
	/* See: https://bugs.chromium.org/p/chromium/issues/detail?id=600120 */
	mix-blend-mode: plus-lighter;
}

.leaflet-container.leaflet-touch-zoom {
	-ms-touch-action: pan-x pan-y;
	touch-action: pan-x pan-y;
	}
.leaflet-container.leaflet-touch-drag {
	-ms-touch-action: pinch-zoom;
	/* Fallback for FF which doesn't support pinch-zoom */
	touch-action: none;
	touch-action: pinch-zoom;
}
.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom {
	-ms-touch-action: none;
	touch-action: none;
}
.leaflet-container {
	-webkit-tap-highlight-color: transparent;
}
.leaflet-container a {
	-webkit-tap-highlight-color: rgba(51, 181, 229, 0.4);
}
.leaflet-tile {
	filter: inherit;
	visibility: hidden;
	}
.leaflet-tile-loaded {
	visibility: inherit;
	}
.leaflet-zoom-box {
	width: 0;
	height: 0;
	-moz-box-sizing: border-box;
	     box-sizing: border-box;
	z-index: 800;
	}
/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
.leaflet-overlay-pane svg {
	-moz-user-select: none;
	}

.leaflet-pane         { z-index: 400; }

.leaflet-tile-pane    { z-index: 200; }
.leaflet-overlay-pane { z-index: 400; }
.leaflet-shadow-pane  { z-index: 500; }
.leaflet-marker-pane  { z-index: 600; }
.leaflet-tooltip-pane   { z-index: 650; }
.leaflet-popup-pane   { z-index: 700; }

.leaflet-map-pane canvas { z-index: 100; }
.leaflet-map-pane svg    { z-index: 200; }

.leaflet-vml-shape {
	width: 1px;
	height: 1px;
	}
.lvml {
	behavior: url(#default#VML);
	display: inline-block;
	position: absolute;
	}


/* control positioning */

.leaflet-control {
	position: relative;
	z-index: 800;
	pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
	pointer-events: auto;
	}
.leaflet-top,
.leaflet-bottom {
	position: absolute;
	z-index: 1000;
	pointer-events: none;
	}
.leaflet-top {
	top: 0;
	}
.leaflet-right {
	right: 0;
	}
.leaflet-bottom {
	bottom: 0;
	}
.leaflet-left {
	left: 0;
	}
.leaflet-control {
	float: left;
	clear: both;
	}
.leaflet-right .leaflet-control {
	float: right;
	}
.leaflet-top .leaflet-control {
	margin-top: 10px;
	}
.leaflet-bottom .leaflet-control {
	margin-bottom: 10px;
	}
.leaflet-left .leaflet-control {
	margin-left: 10px;
	}
.leaflet-right .leaflet-control {
	margin-right: 10px;
	}


/* zoom and fade animations */

.leaflet-fade-anim .leaflet-popup {
	opacity: 0;
	-webkit-transition: opacity 0.2s linear;
	   -moz-transition: opacity 0.2s linear;
	        transition: opacity 0.2s linear;
	}
.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
	opacity: 1;
	}
.leaflet-zoom-animated {
	-webkit-transform-origin: 0 0;
	    -ms-transform-origin: 0 0;
	        transform-origin: 0 0;
	}
svg.leaflet-zoom-animated {
	will-change: transform;
}

.leaflet-zoom-anim .leaflet-zoom-animated {
	-webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
	   -moz-transition:    -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
	        transition:         transform 0.25s cubic-bezier(0,0,0.25,1);
	}
.leaflet-zoom-anim .leaflet-tile,
.leaflet-pan-anim .leaflet-tile {
	-webkit-transition: none;
	   -moz-transition: none;
	        transition: none;
	}

.leaflet-zoom-anim .leaflet-zoom-hide {
	visibility: hidden;
	}


/* cursors */

.leaflet-interactive {
	cursor: pointer;
	}
.leaflet-grab {
	cursor: -webkit-grab;
	cursor:    -moz-grab;
	cursor:         grab;
	}
.leaflet-crosshair,
.leaflet-crosshair .leaflet-interactive {
	cursor: crosshair;
	}
.leaflet-popup-pane,
.leaflet-control {
	cursor: auto;
	}
.leaflet-dragging .leaflet-grab,
.leaflet-dragging .leaflet-grab .leaflet-interactive,
.leaflet-dragging .leaflet-marker-draggable {
	cursor: move;
	cursor: -webkit-grabbing;
	cursor:    -moz-grabbing;
	cursor:         grabbing;
	}

/* marker & overlays interactivity */
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-image-layer,
.leaflet-pane > svg path,
.leaflet-tile-container {
	pointer-events: none;
	}

.leaflet-marker-icon.leaflet-interactive,
.leaflet-image-layer.leaflet-interactive,
.leaflet-pane > svg path.leaflet-interactive,
svg.leaflet-image-layer.leaflet-interactive path {
	pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
	pointer-events: auto;
	}

/* visual tweaks */

.leaflet-container {
	background: #ddd;
	outline-offset: 1px;
	}
.leaflet-container a {
	color: #0078A8;
	}
.leaflet-zoom-box {
	border: 2px dotted #38f;
	background: rgba(255,255,255,0.5);
	}


/* general typography */
.leaflet-container {
	font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
	font-size: 12px;
	font-size: 0.75rem;
	line-height: 1.5;
	}


/* general toolbar styles */

.leaflet-bar {
	box-shadow: 0 1px 5px rgba(0,0,0,0.65);
	border-radius: 4px;
	}
.leaflet-bar a {
	background-color: #fff;
	border-bottom: 1px solid #ccc;
	width: 26px;
	height: 26px;
	line-height: 26px;
	display: block;
	text-align: center;
	text-decoration: none;
	color: black;
	}
.leaflet-bar a,
.leaflet-control-layers-toggle {
	background-position: 50% 50%;
	background-repeat: no-repeat;
	display: block;
	}
.leaflet-bar a:hover,
.leaflet-bar a:focus {
	background-color: #f4f4f4;
	}
.leaflet-bar a:first-child {
	border-top-left-radius: 4px;
	border-top-right-radius: 4px;
	}
.leaflet-bar a:last-child {
	border-bottom-left-radius: 4px;
	border-bottom-right-radius: 4px;
	border-bottom: none;
	}
.leaflet-bar a.leaflet-disabled {
	cursor: default;
	background-color: #f4f4f4;
	color: #bbb;
	}

.leaflet-touch .leaflet-bar a {
	width: 30px;
	height: 30px;
	line-height: 30px;
	}
.leaflet-touch .leaflet-bar a:first-child {
	border-top-left-radius: 2px;
	border-top-right-radius: 2px;
	}
.leaflet-touch .leaflet-bar a:last-child {
	border-bottom-left-radius: 2px;
	border-bottom-right-radius: 2px;
	}

/* zoom control */

.leaflet-control-zoom-in,
.leaflet-control-zoom-out {
	font: bold 18px 'Lucida Console', Monaco, monospace;
	text-indent: 1px;
	}

.leaflet-touch .leaflet-control-zoom-in, .leaflet-touch .leaflet-control-zoom-out  {
	font-size: 22px;
	}


/* layers control */

.leaflet-control-layers {
	box-shadow: 0 1px 5px rgba(0,0,0,0.4);
	background: #fff;
	border-radius: 5px;
	}
.leaflet-control-layers-toggle {
	background-image: url(images/layers.png);
	width: 36px;
	height: 36px;
	}
.leaflet-retina .leaflet-control-layers-toggle {
	background-image: url(images/layers-2x.png);
	background-size: 26px 26px;
	}
.leaflet-touch .leaflet-control-layers-toggle {
	width: 44px;
	height: 44px;
	}
.leaflet-control-layers .leaflet-control-layers-list,
.leaflet-control-layers-expanded .leaflet-control-layers-toggle {
	display: none;
	}
.leaflet-control-layers-expanded .leaflet-control-layers-list {
	display: block;
	position: relative;
	}
.leaflet-control-layers-expanded {
	padding: 6px 10px 6px 6px;
	color: #333;
	background: #fff;
	}
.leaflet-control-layers-scrollbar {
	overflow-y: scroll;
	overflow-x: hidden;
	padding-right: 5px;
	}
.leaflet-control-layers-selector {
	margin-top: 2px;
	position: relative;
	top: 1px;
	}
.leaflet-control-layers label {
	display: block;
	font-size: 13px;
	font-size: 1.08333em;
	}
.leaflet-control-layers-separator {
	height: 0;
	border-top: 1px solid #ddd;
	margin: 5px -10px 5px -6px;
	}

/* Default icon URLs */
.leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */
	background-image: url(images/marker-icon.png);
	}


/* attribution and scale controls */

.leaflet-container .leaflet-control-attribution {
	background: #fff;
	background: rgba(255, 255, 255, 0.8);
	margin: 0;
	}
.leaflet-control-attribution,
.leaflet-control-scale-line {
	padding: 0 5px;
	color: #333;
	line-height: 1.4;
	}
.leaflet-control-attribution a {
	text-decoration: none;
	}
.leaflet-control-attribution a:hover,
.leaflet-control-attribution a:focus {
	text-decoration: underline;
	}
.leaflet-attribution-flag {
	display: inline !important;
	vertical-align: baseline !important;
	width: 1em;
	height: 0.6669em;
	}
.leaflet-left .leaflet-control-scale {
	margin-left: 5px;
	}
.leaflet-bottom .leaflet-control-scale {
	margin-bottom: 5px;
	}
.leaflet-control-scale-line {
	border: 2px solid #777;
	border-top: none;
	line-height: 1.1;
	padding: 2px 5px 1px;
	white-space: nowrap;
	-moz-box-sizing: border-box;
	     box-sizing: border-box;
	background: rgba(255, 255, 255, 0.8);
	text-shadow: 1px 1px #fff;
	}
.leaflet-control-scale-line:not(:first-child) {
	border-top: 2px solid #777;
	border-bottom: none;
	margin-top: -2px;
	}
.leaflet-control-scale-line:not(:first-child):not(:last-child) {
	border-bottom: 2px solid #777;
	}

.leaflet-touch .leaflet-control-attribution,
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
	box-shadow: none;
	}
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
	border: 2px solid rgba(0,0,0,0.2);
	background-clip: padding-box;
	}


/* popup */

.leaflet-popup {
	position: absolute;
	text-align: center;
	margin-bottom: 20px;
	}
.leaflet-popup-content-wrapper {
	padding: 1px;
	text-align: left;
	border-radius: 12px;
	}
.leaflet-popup-content {
	margin: 13px 24px 13px 20px;
	line-height: 1.3;
	font-size: 13px;
	font-size: 1.08333em;
	min-height: 1px;
	}
.leaflet-popup-content p {
	margin: 17px 0;
	margin: 1.3em 0;
	}
.leaflet-popup-tip-container {
	width: 40px;
	height: 20px;
	position: absolute;
	left: 50%;
	margin-top: -1px;
	margin-left: -20px;
	overflow: hidden;
	pointer-events: none;
	}
.leaflet-popup-tip {
	width: 17px;
	height: 17px;
	padding: 1px;

	margin: -10px auto 0;
	pointer-events: auto;

	-webkit-transform: rotate(45deg);
	   -moz-transform: rotate(45deg);
	    -ms-transform: rotate(45deg);
	        transform: rotate(45deg);
	}
.leaflet-popup-content-wrapper,
.leaflet-popup-tip {
	background: white;
	color: #333;
	box-shadow: 0 3px 14px rgba(0,0,0,0.4);
	}
.leaflet-container a.leaflet-popup-close-button {
	position: absolute;
	top: 0;
	right: 0;
	border: none;
	text-align: center;
	width: 24px;
	height: 24px;
	font: 16px/24px Tahoma, Verdana, sans-serif;
	color: #757575;
	text-decoration: none;
	background: transparent;
	}
.leaflet-container a.leaflet-popup-close-button:hover,
.leaflet-container a.leaflet-popup-close-button:focus {
	color: #585858;
	}
.leaflet-popup-scrolled {
	overflow: auto;
	}

.leaflet-oldie .leaflet-popup-content-wrapper {
	-ms-zoom: 1;
	}
.leaflet-oldie .leaflet-popup-tip {
	width: 24px;
	margin: 0 auto;

	-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
	filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
	}

.leaflet-oldie .leaflet-control-zoom,
.leaflet-oldie .leaflet-control-layers,
.leaflet-oldie .leaflet-popup-content-wrapper,
.leaflet-oldie .leaflet-popup-tip {
	border: 1px solid #999;
	}


/* div icon */

.leaflet-div-icon {
	background: #fff;
	border: 1px solid #666;
	}


/* Tooltip */
/* Base styles for the element that has a tooltip */
.leaflet-tooltip {
	position: absolute;
	padding: 6px;
	background-color: #fff;
	border: 1px solid #fff;
	border-radius: 3px;
	color: #222;
	white-space: nowrap;
	-webkit-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
	pointer-events: none;
	box-shadow: 0 1px 3px rgba(0,0,0,0.4);
	}
.leaflet-tooltip.leaflet-interactive {
	cursor: pointer;
	pointer-events: auto;
	}
.leaflet-tooltip-top:before,
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
	position: absolute;
	pointer-events: none;
	border: 6px solid transparent;
	background: transparent;
	content: "";
	}

/* Directions */

.leaflet-tooltip-bottom {
	margin-top: 6px;
}
.leaflet-tooltip-top {
	margin-top: -6px;
}
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-top:before {
	left: 50%;
	margin-left: -6px;
	}
.leaflet-tooltip-top:before {
	bottom: 0;
	margin-bottom: -12px;
	border-top-color: #fff;
	}
.leaflet-tooltip-bottom:before {
	top: 0;
	margin-top: -12px;
	margin-left: -6px;
	border-bottom-color: #fff;
	}
.leaflet-tooltip-left {
	margin-left: -6px;
}
.leaflet-tooltip-right {
	margin-left: 6px;
}
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
	top: 50%;
	margin-top: -6px;
	}
.leaflet-tooltip-left:before {
	right: 0;
	margin-right: -12px;
	border-left-color: #fff;
	}
.leaflet-tooltip-right:before {
	left: 0;
	margin-left: -12px;
	border-right-color: #fff;
	}

/* Printing */

@media print {
	/* Prevent printers from removing background-images of controls. */
	.leaflet-control {
		-webkit-print-color-adjust: exact;
		print-color-adjust: exact;
		}
	}

`;

// src/fdsncommon.mts
var fdsncommon_exports = {};
__export(fdsncommon_exports, {
  EARTHSCOPE_HOST: () => EARTHSCOPE_HOST,
  FDSNCommon: () => FDSNCommon,
  FDSNWS_PATH_BASE: () => FDSNWS_PATH_BASE,
  FDSN_HOST: () => FDSN_HOST,
  IRISWS_PATH_BASE: () => IRISWS_PATH_BASE,
  IRIS_HOST: () => IRIS_HOST,
  LOCALWS_PATH_BASE: () => LOCALWS_PATH_BASE,
  LatLonBox: () => LatLonBox,
  LatLonRadius: () => LatLonRadius,
  LatLonRegion: () => LatLonRegion,
  appendToPath: () => appendToPath,
  defaultPortStringForProtocol: () => defaultPortStringForProtocol,
  protocolForKnownHost: () => protocolForKnownHost
});
var EARTHSCOPE_HOST = "service.earthscope.org";
var IRIS_HOST = EARTHSCOPE_HOST;
var FDSN_HOST = "www.fdsn.org";
var FDSNWS_PATH_BASE = "fdsnws";
var IRISWS_PATH_BASE = "irisws";
var LOCALWS_PATH_BASE = "localws";
var FDSNCommon = class {
  constructor(service, host) {
    this._specVersion = "1";
    this._host = EARTHSCOPE_HOST;
    this._protocol = checkProtocol();
    this._path_base = FDSNWS_PATH_BASE;
    this._service = service;
    if (isNonEmptyStringArg(host)) {
      this._host = host;
    }
    this._port = 80;
    this._timeoutSec = 30;
  }
  defaultPortStringForProtocol(protocol) {
    return defaultPortStringForProtocol(protocol, this._port);
  }
};
function protocolForKnownHost(host, defaultProtocol) {
  switch (host.toLowerCase()) {
    case EARTHSCOPE_HOST:
    case USGS_HOST:
    case FDSN_HOST:
      return "https";
    default:
      return defaultProtocol;
  }
}
function defaultPortStringForProtocol(protocol, port) {
  return (protocol === "http" || protocol === "http:" || protocol === "https" || protocol === "https:") && (port === 80 || port === 443) ? "" : ":" + String(port);
}
function appendToPath(baseUrl, addPath) {
  let out = baseUrl + (baseUrl.endsWith("/") ? "" : "/");
  if (addPath.startsWith("/")) {
    out += addPath.substring(1);
  } else {
    out += addPath;
  }
  return out;
}
var LatLonRegion = class {
};
var LatLonBox = class extends LatLonRegion {
  constructor(west, east, south, north) {
    super();
    this.west = west;
    this.east = east;
    this.south = south;
    this.north = north;
  }
  asLeafletBounds() {
    return [
      [this.south, this.west],
      [this.north, this.east]
    ];
  }
};
var LatLonRadius = class extends LatLonRegion {
  constructor(latitude, longitude, minRadius, maxRadius) {
    super();
    this.latitude = latitude;
    this.longitude = longitude;
    this.minRadius = minRadius;
    this.maxRadius = maxRadius;
  }
};

// src/leafletutil.mts
var L2 = __toESM(require_leaflet_src(), 1);
var HIGHLIGHT = "highlight";
var UNSELECTED = "unselected";
var MAP_ELEMENT = "sp-station-quake-map";
var TRIANGLE = "triangle";
var CIRCLE = "circle";
var DOWNTRIANGLE = "downtriangle";
var SQUARE = "square";
var CROSS = "cross";
var StationMarkerClassName = "stationMapMarker";
var InactiveStationMarkerClassName = "inactiveStationMapMarker";
var QuakeMarkerClassName = "quakeMapMarker";
var STATION_ICON_SIZE = 18;
var stationIcon = L2.divIcon({
  className: StationMarkerClassName,
  iconSize: [STATION_ICON_SIZE, STATION_ICON_SIZE]
});
var inactiveStationIcon = L2.divIcon({
  className: InactiveStationMarkerClassName,
  iconSize: [STATION_ICON_SIZE, STATION_ICON_SIZE]
});
var defaultMapElement_css = `

:host {
  display: block
}

div.wrapper {
  height: 100%;
  min-height: 100px;
}

.leaflet-container {
  height: 100%;
  width: 100%;
}
`;
var defaultMarker_css = `
.${StationMarkerClassName}.${InactiveStationMarkerClassName} {
  fill: darkgrey;
  stroke: darkgrey;
  z-index: 1;
}
.${StationMarkerClassName} {
  z-index: 10;
  fill: royalblue;
  stroke: royalblue;
}
.${StationMarkerClassName} svg  {
  background: none;
}

.${QuakeMarkerClassName} {
  stroke: red;
  fill: #f03;
  fill-opacity: 0.15;
}
.${StationMarkerClassName}.${HIGHLIGHT} {
  stroke: white;
}
.${QuakeMarkerClassName}.${HIGHLIGHT} {
  stroke: white;
}
.${StationMarkerClassName}.${UNSELECTED} {
  fill: lightgrey;
}
.${QuakeMarkerClassName}.${UNSELECTED} {
  stroke: tomato;
}
`;
var stationMarker_css = defaultMarker_css;
function cssClassForStationCodes(station) {
  return `sta_${station.codes(STATION_CODE_SEP)}`;
}
function cssClassForNetworkCode(network) {
  return `net_${network.networkCode}`;
}
function createStationSVG(iconSize = STATION_ICON_SIZE, symbol2 = TRIANGLE) {
  const strokeWidth = 2;
  const xCent = iconSize / 2;
  const yCent = iconSize / 2;
  const shift = (iconSize - strokeWidth) / 2;
  let out = `<svg version="1.2" baseProfile="tiny" xmlns="http://www.w3.org/2000/svg" width="${iconSize}" height="${iconSize}">`;
  if (symbol2 === DOWNTRIANGLE) {
    out += `<polygon points="${xCent},${yCent + shift} ${xCent + shift},${yCent - shift} ${xCent - shift},${yCent - shift}" stroke-width="${strokeWidth}""/>
      `;
  } else if (symbol2 === SQUARE) {
    out += `<polygon points="${xCent - shift},${yCent - shift} ${xCent + shift},${yCent - shift} ${xCent + shift},${yCent + shift} ${xCent - shift},${yCent + shift}" stroke-width="${strokeWidth}""/>
      `;
  } else if (symbol2 === CROSS) {
    out += `<line x1="${xCent - shift}" y1="${yCent}" x2="${xCent + shift}" y2="${yCent}" stroke-width="${strokeWidth}"/>
    <line x1="${xCent}" y1="${yCent - shift}" x2="${xCent}" y2="${yCent + shift}"  stroke-width="${strokeWidth}"/>`;
  } else if (symbol2 === CIRCLE) {
    out += `<circle cx="${xCent}" cy="${yCent}" r="${shift}" stroke-width="${strokeWidth}"/>`;
  } else {
    out += `
    <polygon points="${xCent},${yCent - shift} ${xCent + shift},${yCent + shift} ${xCent - shift},${yCent + shift}" stroke-width="${strokeWidth}""/>
      `;
  }
  out += "</svg>";
  return out;
}
function createStationMarker(station, classList2, isactive = true, centerLon = 0, iconSize = STATION_ICON_SIZE, iconSymbol = TRIANGLE) {
  const allClassList = classList2 != null ? classList2.slice() : [];
  allClassList.push(
    isactive ? StationMarkerClassName : InactiveStationMarkerClassName
  );
  allClassList.push(cssClassForStationCodes(station));
  allClassList.push(cssClassForNetworkCode(station.network));
  const icon = L2.divIcon({
    html: createStationSVG(iconSize, iconSymbol),
    className: allClassList.join(" "),
    iconSize: [iconSize, iconSize],
    iconAnchor: [iconSize / 2, iconSize / 2]
  });
  const sLon = station.longitude - centerLon <= 180 ? station.longitude : station.longitude - 360;
  const m = L2.marker([station.latitude, sLon], {
    icon
  });
  m.bindTooltip(station.codes());
  return m;
}
function getRadiusForMag(magnitude, magScaleFactor) {
  let radius = magnitude ? magnitude * magScaleFactor : 1;
  if (radius < 2) {
    radius = 2;
  }
  return radius;
}
function createQuakeMarker(quake, magScaleFactor = 5, classList2, centerLon = 0, magToRadius = getRadiusForMag) {
  const allClassList = classList2 ? classList2.slice() : [];
  allClassList.push(QuakeMarkerClassName);
  allClassList.push(cssClassForQuake(quake));
  const qLon = quake.longitude - centerLon <= 180 ? quake.longitude : quake.longitude - 360;
  const magnitude = quake.magnitude ? quake.magnitude.mag : 1;
  const radius = magToRadius(magnitude, magScaleFactor);
  const iconSize = 2 * radius + 2;
  const iconSymbol = CIRCLE;
  const icon = L2.divIcon({
    html: createStationSVG(iconSize, iconSymbol),
    className: allClassList.join(" "),
    iconSize: [iconSize, iconSize],
    iconAnchor: [iconSize / 2, iconSize / 2]
  });
  const m = L2.marker([quake.latitude, qLon], {
    icon
  });
  const magStr = quake.magnitude ? quake.magnitude.toString() : "unkn";
  m.bindTooltip(`${quake.time.toISO()} ${magStr}`);
  return m;
}
var leaflet_css2 = leaflet_css;
var TILE_TEMPLATE = "tileUrl";
var DEFAULT_TILE_TEMPLATE = "https://services.arcgisonline.com/arcgis/rest/services/Ocean/World_Ocean_Base/MapServer/tile/{z}/{y}/{x}";
var TILE_ATTRIBUTION = "tileAttribution";
var MAX_ZOOM = "maxZoom";
var DEFAULT_MAX_ZOOM = 17;
var CENTER_LAT = "centerLat";
var DEFAULT_CENTER_LAT = 35;
var CENTER_LON = "centerLon";
var DEFAULT_CENTER_LON = -81;
var ZOOM_LEVEL = "zoomLevel";
var DEFAULT_ZOOM_LEVEL = 1;
var MAG_SCALE = "magScale";
var DEFAULT_MAG_SCALE = 5;
var FIT_BOUNDS = "fitBounds";
var QUAKE_MARKER_STYLE_EL = "quakeMarkerStyle";
var STATION_MARKER_STYLE_EL = "staMarkerStyle";
var STATION_CODE_SEP = "_";
var LEAFLET_CSS_ID = "leafletcss";
var MAP_CSS_ID = "stationquakemapcss";
var MARKER_CSS_ID = "defaultmarkercss";
var QuakeStationMap = class extends SeisPlotElement {
  constructor(seisData, seisConfig) {
    super(seisData, seisConfig);
    this.quakeList = [];
    this.stationList = [];
    this.geoRegionList = [];
    this.mapItems = [];
    this.quakeLayer = L2.layerGroup();
    this.quakeLayerName = "Quakes";
    this.stationLayer = L2.layerGroup();
    this.stationLayerName = "Stations";
    this.stationIconSize = STATION_ICON_SIZE;
    this.stationIconSymbol = TRIANGLE;
    this.map = null;
    this.classToColor = /* @__PURE__ */ new Map();
    this.stationClassMap = /* @__PURE__ */ new Map();
    this.quakeClassMap = /* @__PURE__ */ new Map();
    this.addStyle(leaflet_css2, LEAFLET_CSS_ID);
    this.addStyle(defaultMapElement_css, MAP_CSS_ID);
    this.addStyle(stationMarker_css, MARKER_CSS_ID);
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    this.getShadowRoot().appendChild(wrapper);
  }
  addQuake(quake, classname) {
    const re2 = /\s+/;
    let classList2 = [];
    if (classname && classname.length > 0) {
      classList2 = classname.split(re2);
    }
    if (Array.isArray(quake)) {
      quake.forEach((q) => this.quakeList.push(q));
      classList2.forEach((cn) => {
        quake.forEach((q) => this.quakeAddClass(q, cn));
      });
    } else {
      this.quakeList.push(quake);
      classList2.forEach((cn) => {
        this.quakeAddClass(quake, cn);
      });
    }
  }
  allQuakes() {
    const quakes = this.quakeList.concat(uniqueQuakes(this.seisData));
    return quakes;
  }
  /**
   * Adds a css class for the quake icon for additional styling,
   * either via addStyle() for general or via colorClass() for just
   * simply coloring.
   *
   * @param  quake  the quake
   * @param  classname  css class name
   */
  quakeAddClass(quake, classname) {
    const quakeIdStr = cssClassForQuake(quake);
    const classList2 = this.quakeClassMap.get(quakeIdStr);
    if (classList2) {
      classList2.push(classname);
    } else {
      this.quakeClassMap.set(cssClassForQuake(quake), [classname]);
    }
    const circleList = this.getShadowRoot().querySelectorAll(
      `path.${quakeIdStr}`
    );
    circleList.forEach((c) => {
      c.classList.add(classname);
    });
  }
  /**
   * Removes a css class from the earthquake circle.
   *
   * @param  quake  quake to remove
   * @param  classname   class to remove
   */
  quakeRemoveClass(quake, classname) {
    const quakeIdStr = cssClassForQuake(quake);
    let classList2 = this.quakeClassMap.get(quakeIdStr);
    if (classList2) {
      classList2 = classList2.filter((v) => v !== classname);
      this.quakeClassMap.set(cssClassForQuake(quake), classList2);
    }
    const circleList = this.getShadowRoot().querySelectorAll(
      `path.${quakeIdStr}`
    );
    circleList.forEach((c) => {
      c.classList.remove(classname);
    });
  }
  /**
   * Removes a css class from all earthquake circles.
   *
   * @param  classname   class to remove
   */
  quakeRemoveAllClass(classname) {
    this.allQuakes().forEach((q) => this.quakeRemoveClass(q, classname));
  }
  quakeUnhighlight() {
    this.allQuakes().forEach((q) => {
      this.quakeRemoveClass(q, HIGHLIGHT);
    });
  }
  quakeHighlight(quakeList) {
    if (!Array.isArray(quakeList)) {
      quakeList = [quakeList];
    }
    this.quakeUnhighlight();
    quakeList.forEach((q) => {
      this.quakeAddClass(q, HIGHLIGHT);
    });
  }
  addStation(station, classname) {
    const re2 = /\s+/;
    let classList2 = [];
    if (classname && classname.length > 0) {
      classList2 = classname.split(re2);
    }
    if (Array.isArray(station)) {
      station.forEach((s2) => this.stationList.push(s2));
      classList2.forEach((cn) => {
        station.forEach((s2) => this.stationAddClass(s2, cn));
      });
    } else {
      this.stationList.push(station);
      classList2.forEach((cn) => this.stationAddClass(station, cn));
    }
  }
  /**
   * Get all stations on the map. Some from seisData and some added directly
   * to stationList.
   * @return list of Stations
   */
  allStations() {
    const stations = this.stationList.concat(uniqueStations2(this.seisData));
    return stations;
  }
  stationIcon(iconSize = STATION_ICON_SIZE, iconSymbol = TRIANGLE) {
    this.stationIconSize = iconSize;
    this.stationIconSymbol = iconSymbol;
    if (iconSize < 0) {
      throw new Error(`icon size must be postive number: ${iconSize}`);
    }
  }
  /**
   * Adds a css class for the station icon for additional styling,
   * either via addStyle() for general or via colorClass() for just
   * simply coloring.
   *
   * @param  station  the station
   * @param  classname  css class name
   */
  stationAddClass(station, classname) {
    const classList2 = this.stationClassMap.get(station.codes(STATION_CODE_SEP));
    if (classList2) {
      classList2.push(classname);
    } else {
      this.stationClassMap.set(station.codes(STATION_CODE_SEP), [classname]);
    }
    const markerList = this.getShadowRoot().querySelectorAll(
      `div.${cssClassForStationCodes(station)}`
    );
    markerList.forEach((c) => {
      c.classList.add(classname);
    });
  }
  /**
   * Removes a css class from the station triangle
   *
   * @param  station   the station
   * @param  classname  css class name
   */
  stationRemoveClass(station, classname) {
    let classList2 = this.stationClassMap.get(station.codes(STATION_CODE_SEP));
    if (classList2) {
      classList2 = classList2.filter((v) => v !== classname);
      this.stationClassMap.set(station.codes(STATION_CODE_SEP), classList2);
    }
    const markerList = this.getShadowRoot().querySelectorAll(
      `div.${cssClassForStationCodes(station)}`
    );
    markerList.forEach((c) => {
      c.classList.remove(classname);
    });
  }
  stationUnhighlight() {
    this.allStations().forEach((sta) => {
      this.stationRemoveClass(sta, HIGHLIGHT);
    });
  }
  stationHighlight(stationList) {
    if (!Array.isArray(stationList)) {
      stationList = [stationList];
    }
    this.stationUnhighlight();
    stationList.forEach((sta) => {
      this.stationAddClass(sta, HIGHLIGHT);
    });
  }
  /**
   * Set a color in css for the classname. This is a simple alternative
   * to full styling via addStyle().
   *
   * @param  classname  css class name
   * @param  color      color, like red
   */
  colorClass(classname, color2) {
    this.classToColor.set(classname, color2);
    this.updateQuakeMarkerStyle();
    this.updateStationMarkerStyle();
  }
  removeColorClass(classname) {
    this.classToColor.delete(classname);
    this.updateQuakeMarkerStyle();
    this.updateStationMarkerStyle();
  }
  get fitBounds() {
    const fbAttr = this.hasAttribute(FIT_BOUNDS) ? this.getAttribute(FIT_BOUNDS) : "true";
    let fb;
    if (!fbAttr) {
      fb = true;
    } else {
      fb = fbAttr.toLowerCase() === "true";
    }
    return fb;
  }
  set fitBounds(val) {
    this.setAttribute(FIT_BOUNDS, `${val}`);
  }
  get centerLat() {
    const ks = this.hasAttribute(CENTER_LAT) ? this.getAttribute(CENTER_LAT) : null;
    let k;
    if (!ks) {
      k = DEFAULT_CENTER_LAT;
    } else {
      k = parseFloat(ks);
    }
    return k;
  }
  set centerLat(val) {
    this.setAttribute(CENTER_LAT, `${val}`);
  }
  get centerLon() {
    const ks = this.hasAttribute(CENTER_LON) ? this.getAttribute(CENTER_LON) : null;
    let k;
    if (!ks) {
      k = DEFAULT_CENTER_LON;
    } else {
      k = parseFloat(ks);
    }
    return k;
  }
  set centerLon(val) {
    this.setAttribute(CENTER_LON, `${val}`);
  }
  get zoomLevel() {
    const ks = this.hasAttribute(ZOOM_LEVEL) ? this.getAttribute(ZOOM_LEVEL) : null;
    let k;
    if (!ks) {
      k = DEFAULT_ZOOM_LEVEL;
    } else {
      k = parseInt(ks);
    }
    return k;
  }
  set zoomLevel(val) {
    this.setAttribute(ZOOM_LEVEL, `${val}`);
  }
  get magScale() {
    const ks = this.hasAttribute(MAG_SCALE) ? this.getAttribute(MAG_SCALE) : null;
    let k;
    if (!ks) {
      k = DEFAULT_MAG_SCALE;
    } else {
      k = parseFloat(ks);
    }
    return k;
  }
  set magScale(val) {
    this.setAttribute(MAG_SCALE, `${val}`);
  }
  draw() {
    if (!this.isConnected) {
      return;
    }
    this.updateQuakeMarkerStyle();
    this.updateStationMarkerStyle();
    const wrapper = this.getShadowRoot().querySelector("div");
    while (wrapper.firstChild) {
      wrapper.removeChild(wrapper.lastChild);
    }
    const divElement = wrapper.appendChild(document.createElement("div"));
    const mymap = L2.map(
      divElement,
      { layers: [this.quakeLayer, this.stationLayer] }
    ).setView(
      [this.centerLat, this.centerLon],
      this.zoomLevel
    );
    this.map = mymap;
    if (this.seismographConfig.wheelZoom) {
      mymap.scrollWheelZoom.enable();
    } else {
      mymap.scrollWheelZoom.disable();
    }
    let tileUrl = DEFAULT_TILE_TEMPLATE;
    let maxZoom = DEFAULT_MAX_ZOOM;
    const tileUrlAttr = this.getAttribute(TILE_TEMPLATE);
    if (tileUrlAttr) {
      tileUrl = tileUrlAttr;
    }
    tileUrl = fixProtocolInUrl(tileUrl);
    const maxZoomAttr = this.getAttribute(MAX_ZOOM);
    if (maxZoomAttr) {
      maxZoom = Number.parseInt(maxZoomAttr);
    }
    const tileOptions = {
      maxZoom
    };
    const tileAttributionAttr = this.getAttribute(TILE_ATTRIBUTION);
    if (tileAttributionAttr) {
      tileOptions.attribution = tileAttributionAttr;
    }
    L2.tileLayer(tileUrl, tileOptions).addTo(mymap);
    const regionBounds = this.drawGeoRegions(mymap);
    regionBounds.forEach((b) => this.mapItems.push(b));
    this.drawStationLayer();
    this.drawQuakeLayer();
    if (this.fitBounds && this.mapItems.length > 1) {
      mymap.fitBounds(this.mapItems);
    }
  }
  drawQuakeLayer() {
    this.quakeLayer.clearLayers();
    const quakes = this.allQuakes();
    quakes.forEach((q) => {
      const circle2 = createQuakeMarker(
        q,
        this.magScale,
        this.quakeClassMap.get(cssClassForQuake(q)),
        this.centerLon
      );
      circle2.addTo(this.quakeLayer);
      this.mapItems.push([q.latitude, q.longitude]);
      circle2.addEventListener("click", (evt) => {
        const ce = createQuakeClickEvent(q, evt.originalEvent);
        this.dispatchEvent(ce);
      });
    });
    if (this.map) {
      this.quakeLayer.addTo(this.map);
    }
  }
  drawStationLayer() {
    this.stationLayer.clearLayers();
    const stations = this.allStations();
    stations.forEach((s2) => {
      const m = createStationMarker(
        s2,
        this.stationClassMap.get(s2.codes(STATION_CODE_SEP)),
        true,
        this.centerLon,
        this.stationIconSize,
        this.stationIconSymbol
      );
      m.addTo(this.stationLayer);
      this.mapItems.push([s2.latitude, s2.longitude]);
      m.addEventListener("click", (evt) => {
        const ce = createStationClickEvent(s2, evt.originalEvent);
        this.dispatchEvent(ce);
      });
    });
    if (this.map) {
      this.stationLayer.addTo(this.map);
    }
  }
  updateQuakeMarkerStyle() {
    const quakeMarkerStyle = this.createQuakeMarkerColorStyle();
    const quakeMarkerStyleEl = this.getShadowRoot().querySelector(
      `style#${QUAKE_MARKER_STYLE_EL}`
    );
    if (quakeMarkerStyleEl) {
      quakeMarkerStyleEl.textContent = quakeMarkerStyle;
    } else {
      this.addStyle(quakeMarkerStyle, QUAKE_MARKER_STYLE_EL);
    }
  }
  updateStationMarkerStyle() {
    const staMarkerStyle = this.createStationMarkerColorStyle();
    const staMarkerStyleEl = this.getShadowRoot().querySelector(
      `style#${STATION_MARKER_STYLE_EL}`
    );
    if (staMarkerStyleEl) {
      staMarkerStyleEl.textContent = staMarkerStyle;
    } else {
      this.addStyle(staMarkerStyle, STATION_MARKER_STYLE_EL);
    }
  }
  drawGeoRegions(map4) {
    const outLatLon = [];
    this.geoRegionList.forEach((gr) => {
      if (gr instanceof LatLonBox) {
        const llbox = gr;
        const bounds = llbox.asLeafletBounds();
        const rect = L2.rectangle(bounds, { color: "red", weight: 1 });
        rect.addTo(map4);
        outLatLon.push(bounds[0]);
        outLatLon.push(bounds[1]);
      } else if (gr instanceof LatLonRadius) {
        const llrad = gr;
        outLatLon.push([llrad.latitude, llrad.longitude]);
        if (llrad.minRadius > 0) {
          L2.circle([llrad.latitude, llrad.longitude], {
            radius: llrad.minRadius * 1e3 * kmPerDeg
          }).addTo(map4);
          outLatLon.push([llrad.latitude + llrad.minRadius, llrad.longitude]);
          outLatLon.push([llrad.latitude - llrad.minRadius, llrad.longitude]);
          outLatLon.push([llrad.latitude, llrad.longitude + llrad.minRadius]);
          outLatLon.push([llrad.latitude, llrad.longitude - llrad.minRadius]);
        }
        if (llrad.maxRadius < 180) {
          L2.circle([llrad.latitude, llrad.longitude], {
            radius: llrad.maxRadius * 1e3 * kmPerDeg
          }).addTo(map4);
          outLatLon.push([llrad.latitude + llrad.maxRadius, llrad.longitude]);
          outLatLon.push([llrad.latitude - llrad.maxRadius, llrad.longitude]);
          outLatLon.push([llrad.latitude, llrad.longitude + llrad.maxRadius]);
          outLatLon.push([llrad.latitude, llrad.longitude - llrad.maxRadius]);
        }
      } else if (gr === null) {
      } else {
        throw new Error(`unknown region type: ${String(gr)}`);
      }
    });
    return outLatLon;
  }
  createStationMarkerColorStyle() {
    let style = "";
    this.classToColor.forEach((color2, classname) => {
      style = `${style}
div.leaflet-marker-icon.${StationMarkerClassName}.${classname}  {
  fill: ${color2};
  stroke: ${color2};
}
`;
    });
    return style;
  }
  createQuakeMarkerColorStyle() {
    let style = "";
    this.classToColor.forEach((color2, classname) => {
      style = `${style}
path.${classname} {
    stroke: ${color2};
    fill: ${color2};
}
`;
    });
    return style;
  }
  attributeChangedCallback(_name, _oldValue, _newValue) {
    this.redraw();
  }
  static get observedAttributes() {
    return [
      TILE_TEMPLATE,
      TILE_ATTRIBUTION,
      MAX_ZOOM,
      CENTER_LAT,
      CENTER_LON,
      ZOOM_LEVEL,
      MAG_SCALE,
      FIT_BOUNDS
    ];
  }
};
customElements.define(MAP_ELEMENT, QuakeStationMap);
function cssClassForQuake(q) {
  const badCSSChars = /[^A-Za-z0-9_-]/g;
  let out;
  if (q.eventId && q.eventId.length > 0) {
    out = q.eventId;
  } else {
    out = `${q.origin.time.toISO()}_${q.magnitude.toString()}`;
  }
  return "qid_" + out.replaceAll(badCSSChars, "_");
}

// src/organizeddisplayselect.mts
function createStationFilterId(sdd) {
  return `station_${sdd.networkCode}_${sdd.stationCode}`;
}
function stationFilter(sdd, container) {
  return inputIdFilter(createStationFilterId(sdd), container);
}
function orientFilter(sdd, container) {
  const inputId = `orient_${sdd.sourceId.subsourceCode}`;
  return inputIdFilter(inputId, container);
}
function bandFilter(sdd, container) {
  const inputId = `band_${sdd.sourceId.bandCode}`;
  return inputIdFilter(inputId, container);
}
function gainFilter(sdd, container) {
  const inputId = `gain_${sdd.sourceId.sourceCode}`;
  return inputIdFilter(inputId, container);
}
function createQuakeFilterId(quake) {
  return `quake_${quake.eventId}`;
}
function quakeFilter(sdd, container) {
  return sdd.quakeList.reduce((acc, cur) => {
    return acc && inputIdFilter(createQuakeFilterId(cur), container);
  }, true);
}
function inputIdFilter(inputId, container) {
  let out = true;
  const queryEl = container != null ? container : document;
  const inputEl = queryEl.querySelector(`#${inputId}`);
  if (inputEl != null) {
    out = inputEl.checked;
  }
  return out;
}
function defaultPlotSelect(sdd, container) {
  return stationFilter(sdd, container) && bandFilter(sdd, container) && gainFilter(sdd, container) && orientFilter(sdd, container) && quakeFilter(sdd, container);
}

// src/organizeddisplaytools.mts
var UNDERSCORE = "_";
var TOOLS_HTML = `
<details>
  <summary>Tools</summary>
  <form>
    <fieldset class="plottype">
      <legend>Plot</legend>
      <span>
        <input type="checkbox" name="with_seis" id="with_seis">
        <label for="with_seis">seismograph</label>
      </span>
      <span>
        <input type="checkbox" name="with_map" id="with_map">
        <label for="with_map">map</label>
      </span>
      <span>
        <input type="checkbox" name="with_info" id="with_info">
        <label for="with_info">info</label>
      </span>
    </fieldset>
    <fieldset class="overlay">
    <legend>Overlay:</legend>
    <span>
      <input type="radio" name="overlay" id="overlay_individual" value="individual" checked>
      <label for="overlay_individual">individual</label>
    </span>
    <span>
      <input type="radio" name="overlay" id="overlay_vector" value="vector">
      <label for="overlay_vector">vector</label>
    </span>
    <span>
      <input type="radio" name="overlay" id="overlay_component" value="component">
      <label for="overlay_component">component</label>
    </span>
    <span>
      <input type="radio" name="overlay" id="overlay_station_component" value="stationcomponent">
      <label for="overlay_station_component">station component</label>
    </span>
    <span>
      <input type="radio" name="overlay" id="overlay_station" value="station">
      <label for="overlay_station">station</label>
    </span>
    <span>
      <input type="radio" name="overlay" id="overlay_all" value="all">
      <label for="overlay_all">all</label>
    </span>
    <span>
      <input type="radio" name="overlay" id="overlay_none" value="none">
      <label for="overlay_none">none</label>
    </span>
  </fieldset>

  </form>
</details>
`;
var OrganizedDisplayTools = class extends SeisPlotElement {
  constructor(seisData, seisConfig) {
    super(seisData, seisConfig);
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    wrapper.innerHTML = TOOLS_HTML;
    this.getShadowRoot().appendChild(wrapper);
    this._organizedDisplay = null;
  }
  get organizedDisplay() {
    return this._organizedDisplay;
  }
  set organizedDisplay(orgdisp) {
    this._organizedDisplay = orgdisp;
    this.initCheckboxes(orgdisp);
  }
  initCheckboxes(orgdisp) {
    if (orgdisp) {
      const shadow = this.shadowRoot;
      const doSeisCB = shadow?.querySelector(
        "input#with_seis"
      );
      if (doSeisCB) {
        doSeisCB.checked = orgdisp.map === "true";
      }
      const doMapCB = shadow?.querySelector(
        "input#with_map"
      );
      if (doMapCB) {
        doMapCB.checked = orgdisp.map === "true";
      }
      const doInfoCB = shadow?.querySelector(
        "input#with_info"
      );
      if (doInfoCB) {
        doInfoCB.checked = orgdisp.info === "true";
      }
      shadow?.querySelectorAll("fieldset.overlay input").forEach((i) => {
        const inEl = i;
        inEl.checked = orgdisp.overlayby === inEl.value;
      });
      const details = shadow?.querySelector("div.wrapper details");
      details?.querySelector("fieldset.sort")?.remove();
      details?.appendChild(this.createSortCheckboxes(orgdisp));
      const select = document.createElement("fieldset");
      select.classList.add("selection");
      const selectlegend = document.createElement("legend");
      selectlegend.textContent = "Select:";
      select.appendChild(selectlegend);
      details?.appendChild(select);
      select.querySelector("fieldset.stations")?.remove();
      select.appendChild(this.createStationCheckboxes(orgdisp));
      select.querySelector("fieldset.orientations")?.remove();
      select.appendChild(this.createOrientationCheckboxes(orgdisp));
      select.querySelector("fieldset.quakes")?.remove();
      select.appendChild(this.createQuakeCheckboxes(orgdisp));
    }
  }
  createSortCheckboxes(orgdisp) {
    const sortFS = document.createElement("fieldset");
    sortFS.classList.add("sort");
    const legend = document.createElement("legend");
    legend.textContent = "Sort:";
    sortFS.appendChild(legend);
    const sortKeyList = Array.from(orgdisp._sorting.keys());
    sortKeyList.push("none");
    for (const sortKey of sortKeyList) {
      const span = document.createElement("span");
      const input = document.createElement("input");
      input.setAttribute("type", "radio");
      input.setAttribute("name", "sort");
      input.setAttribute("id", `sort_${sortKey}`);
      input.setAttribute("value", sortKey);
      input.checked = orgdisp.sortby === input.value;
      input.addEventListener("change", (_e) => {
        if (this._organizedDisplay) {
          this._organizedDisplay?.setAttribute("sort", input.value);
        }
      });
      span.appendChild(input);
      const label = document.createElement("label");
      label.setAttribute("for", `sort_${sortKey}`);
      label.textContent = sortKey;
      span.appendChild(label);
      sortFS.appendChild(span);
    }
    return sortFS;
  }
  createStationCheckboxes(orgdisp) {
    const staDiv = document.createElement("fieldset");
    staDiv.classList.add("stations");
    const staDivLabel = document.createElement("legend");
    staDivLabel.textContent = "Station:";
    staDiv.appendChild(staDivLabel);
    this.updateStationCheckboxes(orgdisp);
    return staDiv;
  }
  updateCheckboxes(orgdisp) {
    this.updateStationCheckboxes(orgdisp);
    this.updateOrientationCheckboxes(orgdisp);
    this.updateQuakeCheckboxes(orgdisp);
  }
  allStationCheckboxes() {
    const div = this.shadowRoot?.querySelector("fieldset.stations");
    if (div == null) {
      return [];
    }
    return div.querySelectorAll("input");
  }
  updateStationCheckboxes(orgdisp) {
    const staDiv = this.shadowRoot?.querySelector("fieldset.stations");
    if (staDiv === null) {
      return;
    }
    const stations = uniqueStations2(orgdisp.sortedSeisData());
    stations.forEach((sta) => {
      const display = sta.codes(UNDERSCORE);
      const key = `station_${display}`;
      const name = "station";
      let foundSta = false;
      staDiv.querySelectorAll("input").forEach((cb) => {
        if (cb.value === key) {
          foundSta = true;
        }
      });
      if (!foundSta) {
        this.createCheckbox(staDiv, name, key, display);
      }
    });
  }
  createCheckbox(staDiv, name, key, display) {
    if (display == null) {
      display = key;
    }
    const span = document.createElement("span");
    const input = document.createElement("input");
    input.setAttribute("type", "checkbox");
    input.setAttribute("name", name);
    input.setAttribute("id", key);
    input.setAttribute("value", key);
    input.checked = true;
    input.addEventListener("change", (_e) => {
      if (this._organizedDisplay) {
        this._organizedDisplay.redraw();
      }
    });
    span.appendChild(input);
    const label = document.createElement("label");
    label.setAttribute("for", key);
    label.textContent = display;
    span.appendChild(label);
    staDiv.appendChild(span);
    return input;
  }
  createOrientationCheckboxes(orgdisp) {
    const orientDiv = document.createElement("fieldset");
    orientDiv.classList.add("orientations");
    const orientDivLabel = document.createElement("legend");
    orientDivLabel.textContent = "Orientation:";
    orientDiv.appendChild(orientDivLabel);
    this.updateOrientationCheckboxes(orgdisp);
    return orientDiv;
  }
  allOrientationCheckboxes() {
    const div = this.shadowRoot?.querySelector("fieldset.orientations");
    if (div == null) {
      return [];
    }
    return div.querySelectorAll("input");
  }
  updateOrientationCheckboxes(orgdisp) {
    const div = this.shadowRoot?.querySelector("fieldset.orientations");
    if (div == null) {
      return;
    }
    const orientations = uniqueSubsourceCodes(orgdisp.sortedSeisData()).sort();
    orientations.forEach((orient) => {
      const key = `orient_${orient}`;
      const name = "orientation";
      let found = false;
      div.querySelectorAll("input").forEach((cb) => {
        if (cb.value === key) {
          found = true;
        }
      });
      if (!found) {
        this.createCheckbox(div, name, key, orient);
      }
    });
  }
  createQuakeCheckboxes(orgdisp) {
    const quakeDiv = document.createElement("fieldset");
    quakeDiv.classList.add("quakes");
    const quakeDivLabel = document.createElement("legend");
    quakeDivLabel.textContent = "Earthquake:";
    quakeDiv.appendChild(quakeDivLabel);
    this.updateQuakeCheckboxes(orgdisp);
    return quakeDiv;
  }
  allQuakeCheckboxes() {
    const div = this.shadowRoot?.querySelector("fieldset.quakes");
    if (div == null) {
      return [];
    }
    return div.querySelectorAll("input");
  }
  updateQuakeCheckboxes(orgdisp) {
    const div = this.shadowRoot?.querySelector("fieldset.quakes");
    if (div === null) {
      return;
    }
    const quakes = uniqueQuakes(orgdisp.sortedSeisData());
    quakes.forEach((quake) => {
      const key = createQuakeFilterId(quake);
      const name = "quake";
      let found = false;
      div.querySelectorAll("input").forEach((cb) => {
        if (cb.value === key) {
          found = true;
        }
      });
      if (!found) {
        this.createCheckbox(
          div,
          name,
          key,
          `${quake.hasMagnitude() ? quake.magnitude.mag : ""} ${quake.time.toISO({ includeOffset: false })}`
        );
      }
    });
  }
  draw() {
    const wrapper = this.getShadowRoot().querySelector("div");
    wrapper.innerHTML = TOOLS_HTML;
    this.wireComponents();
  }
  wireComponents() {
    const shadow = this.shadowRoot;
    const doMapCB = shadow?.querySelector("input#with_map");
    doMapCB?.addEventListener("change", () => {
      if (this._organizedDisplay) {
        this._organizedDisplay.map = doMapCB.checked ? "true" : "false";
      }
    });
    const doInfoCB = shadow?.querySelector(
      "input#with_info"
    );
    doInfoCB?.addEventListener("change", () => {
      if (this._organizedDisplay) {
        this._organizedDisplay.info = `${doInfoCB.checked}`;
      }
    });
    shadow?.querySelectorAll("fieldset.overlay input").forEach((i) => {
      const inEl = i;
      inEl.addEventListener("change", (_e) => {
        if (this._organizedDisplay) {
          this._organizedDisplay?.setAttribute("overlay", inEl.value);
        }
      });
    });
    shadow?.querySelectorAll("fieldset.sort input").forEach((i) => {
      const inEl = i;
      inEl.addEventListener("change", (_e) => {
        if (this._organizedDisplay) {
          this._organizedDisplay?.setAttribute("sort", inEl.value);
        }
      });
    });
    this.initCheckboxes(this._organizedDisplay);
  }
};
var ORG_DISP_TOOLS_ELEMENT = "sp-orgdisp-tools";
customElements.define(ORG_DISP_TOOLS_ELEMENT, OrganizedDisplayTools);

// src/fft.mts
var fft_exports = {};
__export(fft_exports, {
  FFTResult: () => FFTResult,
  calcDFT: () => calcDFT,
  fftForward: () => fftForward,
  findPowerTwo: () => findPowerTwo,
  inverseDFT: () => inverseDFT
});
function fftForward(seis) {
  let sdd;
  if (seis instanceof Seismogram) {
    sdd = SeismogramDisplayData.fromSeismogram(seis);
  } else {
    sdd = seis;
  }
  if (isDef(sdd.seismogram)) {
    const seismogram = sdd.seismogram;
    if (seismogram.isContiguous()) {
      const result = FFTResult.createFromPackedFreq(
        calcDFT(seismogram.y),
        seismogram.numPoints,
        seismogram.sampleRate
      );
      result.seismogramDisplayData = sdd;
      return result;
    } else {
      throw new Error("Can only take FFT is seismogram is contiguous.");
    }
  } else {
    throw new Error("Can not take FFT is seismogram is null.");
  }
}
function calcDFT(timeseries) {
  let [N, log2N] = findPowerTwo(timeseries.length);
  if (N < 16) {
    log2N = 4;
    N = 16;
  }
  const dft = new RDFT(log2N);
  const inArray = new Float32Array(N);
  inArray.fill(0);
  for (let i = 0; i < timeseries.length; i++) {
    inArray[i] = timeseries[i];
  }
  const out = new Float32Array(N).fill(0);
  dft.evaluate(inArray, out);
  return out;
}
function inverseDFT(packedFreq, numPoints) {
  if (numPoints > packedFreq.length) {
    throw new Error(
      `Not enough points in packed freq array for ${numPoints}, only ${packedFreq.length}`
    );
  }
  let [N, log2N] = findPowerTwo(packedFreq.length);
  if (N < 16) {
    log2N = 4;
    N = 16;
  }
  if (N !== packedFreq.length) {
    throw new Error(`power of two check fails: ${N} ${packedFreq.length}`);
  }
  const dft = new RDFT(log2N);
  const out = new Float32Array(N).fill(0);
  dft.evaluateInverse(packedFreq, out);
  return out.slice(0, numPoints);
}
function findPowerTwo(fftlength) {
  let log2N = 1;
  let N = 2;
  while (N < fftlength) {
    log2N += 1;
    N = 2 * N;
  }
  return [N, log2N];
}
var FFTResult = class _FFTResult {
  constructor(origLength, sampleRate) {
    this.origLength = origLength;
    this.sampleRate = sampleRate;
    this.packedFreq = new Float32Array(0);
    this.numPoints = 0;
  }
  /**
   * Factory method to create FFTResult from packed array.
   *
   * @param   packedFreq real and imag values in packed format
   * @param   origLength length of the original timeseries before padding.
   * @param   sampleRate sample rate of original data
   * @returns            FFTResult
   */
  static createFromPackedFreq(packedFreq, origLength, sampleRate) {
    const fftResult = new _FFTResult(origLength, sampleRate);
    fftResult.packedFreq = packedFreq;
    fftResult.numPoints = packedFreq.length;
    const [N, log2N] = findPowerTwo(packedFreq.length);
    if (N < origLength) {
      throw new Error(
        `Not enough freq points, ${packedFreq.length}, for orig length of ${origLength}, must be > and power two, (${N}, ${log2N})`
      );
    }
    return fftResult;
  }
  /**
   * Factory method to create from array of complex numbers.
   *
   * @param   complexArray real and imag values as array of Complex objects.
   * @param   origLength   length of the original timeseries before padding.
   * @param   sampleRate sample rate of original data
   * @returns               FFTResult
   */
  static createFromComplex(complexArray, origLength, sampleRate) {
    const N = 2 * (complexArray.length - 1);
    const modFreq = new Float32Array(N).fill(0);
    modFreq[0] = complexArray[0].real();
    for (let i = 1; i < complexArray.length - 1; i++) {
      modFreq[i] = complexArray[i].real();
      modFreq[N - i] = complexArray[i].imag();
    }
    modFreq[N / 2] = complexArray[complexArray.length - 1].real();
    return _FFTResult.createFromPackedFreq(modFreq, origLength, sampleRate);
  }
  /**
   * Factory method to create from amp and phase arrays
   *
   * @param   amp        amplitude values
   * @param   phase      phase values
   * @param   origLength length of the original timeseries before padding.
   * @param   sampleRate sample rate of original data
   * @returns             FFTResult
   */
  static createFromAmpPhase(amp, phase, origLength, sampleRate) {
    if (amp.length !== phase.length) {
      throw new Error(
        `amp and phase must be same length: ${amp.length} ${phase.length}`
      );
    }
    const modComplex = new Array(amp.length);
    for (let i = 0; i < amp.length; i++) {
      modComplex[i] = complexFromPolar(amp[i], phase[i]);
    }
    return _FFTResult.createFromComplex(modComplex, origLength, sampleRate);
  }
  /**
   * The minimum non-zero frequency in the fft
   *
   * @returns fundamental frequency
   */
  get fundamentalFrequency() {
    if (this.sampleRate) {
      return this.sampleRate / this.numPoints;
    } else {
      throw new Error(
        "sample rate not set on FFTResult, needed to calc min frequency"
      );
    }
  }
  asComplex() {
    const complexArray = [];
    const L3 = this.packedFreq.length;
    complexArray.push(new Complex(this.packedFreq[0], 0));
    for (let i = 1; i < this.packedFreq.length / 2; i++) {
      const c = new Complex(this.packedFreq[i], this.packedFreq[L3 - i]);
      complexArray.push(c);
    }
    complexArray.push(new Complex(this.packedFreq[L3 / 2], 0));
    return complexArray;
  }
  asAmpPhase() {
    const amp = new Float32Array(1 + this.packedFreq.length / 2);
    const phase = new Float32Array(1 + this.packedFreq.length / 2);
    let c = new Complex(this.packedFreq[0], 0);
    amp[0] = c.abs();
    phase[0] = c.angle();
    const L3 = this.packedFreq.length;
    for (let i = 1; i < this.packedFreq.length / 2; i++) {
      c = new Complex(this.packedFreq[i], this.packedFreq[L3 - i]);
      amp[i] = c.abs();
      phase[i] = c.angle();
    }
    c = new Complex(this.packedFreq[L3 / 2], 0);
    amp[this.packedFreq.length / 2] = c.abs();
    phase[this.packedFreq.length / 2] = c.angle();
    return [amp, phase];
  }
  /**
   * calculates the inverse fft of this.packedFreq
   *
   * @returns time domain representation
   */
  fftInverse() {
    return inverseDFT(this.packedFreq, this.origLength);
  }
  frequencies() {
    const out = new Float32Array(this.numPoints / 2 + 1).fill(0);
    for (let i = 0; i < out.length; i++) {
      out[i] = i * this.fundamentalFrequency;
    }
    return out;
  }
  get numFrequencies() {
    return this.numPoints / 2 + 1;
  }
  get minFrequency() {
    return this.fundamentalFrequency;
  }
  get maxFrequency() {
    return this.sampleRate / 2;
  }
  amplitudes() {
    const [amp] = this.asAmpPhase();
    return amp;
  }
  phases() {
    const [, phase] = this.asAmpPhase();
    return phase;
  }
  clone() {
    const out = _FFTResult.createFromPackedFreq(
      this.packedFreq.slice(),
      this.origLength,
      this.sampleRate
    );
    out.seismogramDisplayData = this.seismogramDisplayData;
    return out;
  }
};

// src/spectraplot.mts
var spectraplot_exports = {};
__export(spectraplot_exports, {
  AMPLITUDE: () => AMPLITUDE,
  FreqAmp: () => FreqAmp,
  KIND: () => KIND,
  LOGFREQ: () => LOGFREQ,
  PHASE: () => PHASE,
  SPECTRA_ELEMENT: () => SPECTRA_ELEMENT,
  SpectraPlot: () => SpectraPlot,
  spectra_plot_css: () => spectra_plot_css
});

// src/seismograph.mts
var seismograph_exports = {};
__export(seismograph_exports, {
  COLOR_CSS_ID: () => COLOR_CSS_ID,
  SEISMOGRAPH_ELEMENT: () => SEISMOGRAPH_ELEMENT,
  SEIS_CLICK_EVENT: () => SEIS_CLICK_EVENT,
  SEIS_MOVE_EVENT: () => SEIS_MOVE_EVENT,
  Seismograph: () => Seismograph,
  SeismographAmplitudeScalable: () => SeismographAmplitudeScalable,
  SeismographTimeScalable: () => SeismographTimeScalable,
  ZERO_DURATION: () => ZERO_DURATION,
  createDateFormatWrapper: () => createDateFormatWrapper,
  createFullMarkersForQuakeAtChannel: () => createFullMarkersForQuakeAtChannel,
  createFullMarkersForQuakeAtStation: () => createFullMarkersForQuakeAtStation,
  createMarkerForOriginTime: () => createMarkerForOriginTime,
  createMarkerForPicks: () => createMarkerForPicks,
  createMarkerForQuakePicks: () => createMarkerForQuakePicks,
  createMarkersForTravelTimes: () => createMarkersForTravelTimes,
  createNumberFormatWrapper: () => createNumberFormatWrapper,
  seismograph_css: () => seismograph_css
});

// node_modules/d3-axis/src/identity.js
function identity_default2(x2) {
  return x2;
}

// node_modules/d3-axis/src/axis.js
var top = 1;
var right = 2;
var bottom = 3;
var left = 4;
var epsilon = 1e-6;
function translateX(x2) {
  return "translate(" + x2 + ",0)";
}
function translateY(y2) {
  return "translate(0," + y2 + ")";
}
function number4(scale) {
  return (d) => +scale(d);
}
function center(scale, offset2) {
  offset2 = Math.max(0, scale.bandwidth() - offset2 * 2) / 2;
  if (scale.round()) offset2 = Math.round(offset2);
  return (d) => +scale(d) + offset2;
}
function entering() {
  return !this.__axis;
}
function axis(orient, scale) {
  var tickArguments = [], tickValues = null, tickFormat2 = null, tickSizeInner = 6, tickSizeOuter = 6, tickPadding = 3, offset2 = typeof window !== "undefined" && window.devicePixelRatio > 1 ? 0 : 0.5, k = orient === top || orient === left ? -1 : 1, x2 = orient === left || orient === right ? "x" : "y", transform2 = orient === top || orient === bottom ? translateX : translateY;
  function axis2(context) {
    var values = tickValues == null ? scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain() : tickValues, format2 = tickFormat2 == null ? scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : identity_default2 : tickFormat2, spacing = Math.max(tickSizeInner, 0) + tickPadding, range = scale.range(), range0 = +range[0] + offset2, range1 = +range[range.length - 1] + offset2, position = (scale.bandwidth ? center : number4)(scale.copy(), offset2), selection2 = context.selection ? context.selection() : context, path2 = selection2.selectAll(".domain").data([null]), tick = selection2.selectAll(".tick").data(values, scale).order(), tickExit = tick.exit(), tickEnter = tick.enter().append("g").attr("class", "tick"), line = tick.select("line"), text = tick.select("text");
    path2 = path2.merge(path2.enter().insert("path", ".tick").attr("class", "domain").attr("stroke", "currentColor"));
    tick = tick.merge(tickEnter);
    line = line.merge(tickEnter.append("line").attr("stroke", "currentColor").attr(x2 + "2", k * tickSizeInner));
    text = text.merge(tickEnter.append("text").attr("fill", "currentColor").attr(x2, k * spacing).attr("dy", orient === top ? "0em" : orient === bottom ? "0.71em" : "0.32em"));
    if (context !== selection2) {
      path2 = path2.transition(context);
      tick = tick.transition(context);
      line = line.transition(context);
      text = text.transition(context);
      tickExit = tickExit.transition(context).attr("opacity", epsilon).attr("transform", function(d) {
        return isFinite(d = position(d)) ? transform2(d + offset2) : this.getAttribute("transform");
      });
      tickEnter.attr("opacity", epsilon).attr("transform", function(d) {
        var p = this.parentNode.__axis;
        return transform2((p && isFinite(p = p(d)) ? p : position(d)) + offset2);
      });
    }
    tickExit.remove();
    path2.attr("d", orient === left || orient === right ? tickSizeOuter ? "M" + k * tickSizeOuter + "," + range0 + "H" + offset2 + "V" + range1 + "H" + k * tickSizeOuter : "M" + offset2 + "," + range0 + "V" + range1 : tickSizeOuter ? "M" + range0 + "," + k * tickSizeOuter + "V" + offset2 + "H" + range1 + "V" + k * tickSizeOuter : "M" + range0 + "," + offset2 + "H" + range1);
    tick.attr("opacity", 1).attr("transform", function(d) {
      return transform2(position(d) + offset2);
    });
    line.attr(x2 + "2", k * tickSizeInner);
    text.attr(x2, k * spacing).text(format2);
    selection2.filter(entering).attr("fill", "none").attr("font-size", 10).attr("font-family", "sans-serif").attr("text-anchor", orient === right ? "start" : orient === left ? "end" : "middle");
    selection2.each(function() {
      this.__axis = position;
    });
  }
  axis2.scale = function(_) {
    return arguments.length ? (scale = _, axis2) : scale;
  };
  axis2.ticks = function() {
    return tickArguments = Array.from(arguments), axis2;
  };
  axis2.tickArguments = function(_) {
    return arguments.length ? (tickArguments = _ == null ? [] : Array.from(_), axis2) : tickArguments.slice();
  };
  axis2.tickValues = function(_) {
    return arguments.length ? (tickValues = _ == null ? null : Array.from(_), axis2) : tickValues && tickValues.slice();
  };
  axis2.tickFormat = function(_) {
    return arguments.length ? (tickFormat2 = _, axis2) : tickFormat2;
  };
  axis2.tickSize = function(_) {
    return arguments.length ? (tickSizeInner = tickSizeOuter = +_, axis2) : tickSizeInner;
  };
  axis2.tickSizeInner = function(_) {
    return arguments.length ? (tickSizeInner = +_, axis2) : tickSizeInner;
  };
  axis2.tickSizeOuter = function(_) {
    return arguments.length ? (tickSizeOuter = +_, axis2) : tickSizeOuter;
  };
  axis2.tickPadding = function(_) {
    return arguments.length ? (tickPadding = +_, axis2) : tickPadding;
  };
  axis2.offset = function(_) {
    return arguments.length ? (offset2 = +_, axis2) : offset2;
  };
  return axis2;
}
function axisTop(scale) {
  return axis(top, scale);
}
function axisRight(scale) {
  return axis(right, scale);
}
function axisBottom(scale) {
  return axis(bottom, scale);
}
function axisLeft(scale) {
  return axis(left, scale);
}

// src/seismographmarker.mts
var seismographmarker_exports = {};
__export(seismographmarker_exports, {
  MARKERTYPE_PICK: () => MARKERTYPE_PICK,
  MARKERTYPE_PREDICTED: () => MARKERTYPE_PREDICTED,
  createFullMarkersForQuakeAtChannel: () => createFullMarkersForQuakeAtChannel,
  createFullMarkersForQuakeAtStation: () => createFullMarkersForQuakeAtStation,
  createMarkerForOriginTime: () => createMarkerForOriginTime,
  createMarkerForPicks: () => createMarkerForPicks,
  createMarkerForQuakePicks: () => createMarkerForQuakePicks,
  createMarkersForTravelTimes: () => createMarkersForTravelTimes,
  isValidMarker: () => isValidMarker
});
var MARKERTYPE_PICK = "pick";
var MARKERTYPE_PREDICTED = "predicted";
function isValidMarker(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const m = v;
  return typeof m.time === "string" && typeof m.name === "string" && typeof m.markertype === "string" && typeof m.description === "string" && (!("link" in m) || typeof m.link === "string");
}
function createMarkersForTravelTimes(quake, ttime) {
  return ttime.arrivals.map((a) => {
    return {
      markertype: MARKERTYPE_PREDICTED,
      name: a.phase,
      time: quake.time.plus(Duration.fromMillis(1e3 * a.time)),
      description: ""
    };
  });
}
function createMarkerForOriginTime(quake) {
  return {
    markertype: MARKERTYPE_PREDICTED,
    name: "origin",
    time: quake.time,
    description: ""
  };
}
function createFullMarkersForQuakeAtStation(quake, station) {
  const markers = [];
  if (quake.hasOrigin()) {
    const daz = distaz(
      station.latitude,
      station.longitude,
      quake.latitude,
      quake.longitude
    );
    let magVal = "";
    let magStr = "";
    if (quake.hasPreferredMagnitude()) {
      magVal = quake.preferredMagnitude ? `${quake.preferredMagnitude.mag}` : "";
      magStr = quake.preferredMagnitude ? quake.preferredMagnitude.toString() : "";
    }
    markers.push({
      markertype: MARKERTYPE_PREDICTED,
      name: `M${magVal} ${quake.time.toFormat("HH:mm")}`,
      time: quake.time,
      link: `https://earthquake.usgs.gov/earthquakes/eventpage/${quake.eventId}/executive`,
      description: `${quake.time.toISO()}
${quake.latitude.toFixed(2)}/${quake.longitude.toFixed(2)} ${(quake.depth / 1e3).toFixed(2)} km
${quake.description}
${magStr}
${daz.delta.toFixed(2)} deg to ${station.stationCode} (${daz.distanceKm} km)
`
    });
  }
  return markers;
}
function createFullMarkersForQuakeAtChannel(quake, channel) {
  let markers = createFullMarkersForQuakeAtStation(quake, channel.station);
  if (quake.preferredOrigin) {
    markers = markers.concat(
      createMarkerForPicks(quake.preferredOrigin, channel)
    );
  }
  return markers;
}
function createMarkerForQuakePicks(quake, channel) {
  const markers = [];
  if (quake.pickList) {
    quake.pickList.forEach((pick3) => {
      if (pick3 && pick3.isOnChannel(channel)) {
        markers.push({
          markertype: MARKERTYPE_PICK,
          name: "pick",
          time: pick3.time,
          description: ""
        });
      }
    });
  }
  return markers;
}
function createMarkerForPicks(origin, channel) {
  const markers = [];
  if (origin.arrivals) {
    origin.arrivals.forEach((arrival) => {
      if (arrival && arrival.pick.isOnChannel(channel)) {
        markers.push({
          markertype: MARKERTYPE_PICK,
          name: arrival.phase,
          time: arrival.pick.time,
          description: ""
        });
      }
    });
  }
  return markers;
}

// src/seismograph.mts
registerHelpers();
var CLIP_PREFIX = "seismographclip";
var SEIS_CLICK_EVENT = "seisclick";
var SEIS_MOVE_EVENT = "seismousemove";
var SEISMOGRAPH_ELEMENT = "sp-seismograph";
var seismograph_css = `

:host {
  display: block;
  min-height: 50px;
  height: 100%;
}

div.wrapper {
  min-height: 50px;
  height: 100%;
}

@property --sp-seismograph-is-xlabel {
  syntax: "<number>";
  inherits: true;
  initial-value: 1;
}

@property --sp-seismograph-is-xsublabel {
  syntax: "<number>";
  inherits: true;
  initial-value: 1;
}

@property --sp-seismograph-is-ylabel {
  syntax: "<number>";
  inherits: true;
  initial-value: 1;
}

@property --sp-seismograph-is-ysublabel {
  syntax: "<number>";
  inherits: true;
  initial-value: 1;
}

@property --sp-seismograph-display-title {
  syntax: "<number>";
  inherits: true;
  initial-value: 1;
}

.marker {
  opacity: 0.4;
}

.marker .markerpath {
  fill: none;
  stroke: black;
  stroke-width: 1px;
}

.marker polygon {
  fill: rgba(150,220,150,.4);
}

.marker.predicted polygon {
  fill: rgba(220,220,220,.4);
}

.marker.pick polygon {
  fill: rgba(255,100,100,.4);
}

path.seispath {
  stroke: skyblue;
  fill: none;
  stroke-width: 1px;
}

path.orientZ {
  stroke: seagreen;
}

path.orientN {
  stroke: cornflowerblue;
}

path.orientE {
  stroke: orange;
}

path.alignment {
  stroke-dasharray: 8;
  stroke-width: 2px;
}

svg.seismograph {
  height: 100%;
  width: 100%;
  min-height: 25px;
  min-width: 25px;
}

svg.seismograph g.ySublabel text {
  font-size: smaller;
}

svg.seismograph g.xSublabel text {
  font-size: smaller;
}

svg.seismograph text.title {
  font-size: larger;
  font-weight: bold;
  fill: black;
  color: black;
}

svg.realtimePlot g.allseismograms path.seispath {
  stroke: skyblue;
}

/* links in svg */
svg.seismograph text a {
  fill: #0000EE;
  text-decoration: underline;
}


`;
var COLOR_CSS_ID = "seismographcolors";
var Seismograph = class _Seismograph extends SeisPlotElement {
  constructor(seisData, seisConfig) {
    super(seisData, seisConfig);
    this.minmax_sample_pixels = DEFAULT_MAX_SAMPLE_PER_PIXEL;
    this.outerWidth = -1;
    this.outerHeight = -1;
    this.throttleRescale = null;
    this.throttleRedraw = null;
    this.plotId = ++_Seismograph._lastID;
    this.beforeFirstDraw = true;
    this._debugAlignmentSeisData = [];
    this.width = 200;
    this.height = 100;
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    this.addStyle(seismograph_css);
    const lineColorsCSS = this.seismographConfig.createCSSForLineColors();
    this.addStyle(lineColorsCSS, COLOR_CSS_ID);
    this.getShadowRoot().appendChild(wrapper);
    this.canvas = null;
    this.canvasHolder = null;
    this.svg = select_default2(wrapper).append("svg").style("z-index", 100);
    const svgNode2 = this.svg.node();
    if (svgNode2 != null) {
      wrapper.appendChild(svgNode2);
    }
    if (isDef(this.seismographConfig.minHeight) && isNumArg(this.seismographConfig.minHeight) && this.seismographConfig.minHeight > 0) {
      const minHeight = this.seismographConfig.minHeight;
      this.svg.style("min-height", minHeight + "px");
    }
    if (isNumArg(this.seismographConfig.maxHeight) && this.seismographConfig.maxHeight > 0) {
      this.svg.style("max-height", this.seismographConfig.maxHeight + "px");
    }
    if (isNumArg(this.seismographConfig.minWidth) && this.seismographConfig.minWidth > 0) {
      const minWidth = this.seismographConfig.minWidth;
      this.svg.style("min-width", minWidth + "px");
    }
    if (isNumArg(this.seismographConfig.maxWidth) && this.seismographConfig.maxWidth > 0) {
      this.svg.style("max-width", this.seismographConfig.maxWidth + "px");
    }
    this.svg.classed("seismograph", true);
    this.svg.classed(AUTO_COLOR_SELECTOR, true);
    this.svg.attr("plotId", this.plotId);
    const alignmentTimeOffset = Duration.fromMillis(0);
    const maxDuration = findMaxDuration(this.seisData);
    this.time_scalable = new SeismographTimeScalable(
      this,
      alignmentTimeOffset,
      maxDuration
    );
    if (isDef(this.seismographConfig.linkedTimeScale)) {
      this.seismographConfig.linkedTimeScale.link(this.time_scalable);
    }
    this.calcTimeScaleDomain();
    this.amp_scalable = new SeismographAmplitudeScalable(this);
    if (this.seismographConfig.linkedAmplitudeScale) {
      this.seismographConfig.linkedAmplitudeScale.link(this.amp_scalable);
    }
    this.redoDisplayYScale();
    this.g = this.svg.append("g").classed("marginTransform", true).attr(
      "transform",
      "translate(" + this.seismographConfig.margin.left + "," + this.seismographConfig.margin.top + ")"
    );
    this.g.append("g").classed("allseismograms", true).classed(AUTO_COLOR_SELECTOR, true);
    this.g.append("g").attr("class", "allmarkers").attr("style", "clip-path: url(#" + CLIP_PREFIX + this.plotId + ")");
    this._resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        if (entry.target instanceof _Seismograph) {
          const graph = entry.target;
          const rect = entry.contentRect;
          if (!graph.beforeFirstDraw && (rect.width !== graph.outerWidth || rect.height !== graph.outerHeight)) {
            graph.redraw();
          }
        }
      }
    });
    this._resizeObserver.observe(this);
    this.addEventListener("click", (evt) => {
      const detail = this.calcDetailForEvent(evt, "click");
      const event = new CustomEvent(
        SEIS_CLICK_EVENT,
        {
          detail,
          bubbles: true,
          cancelable: false,
          composed: true
        }
      );
      this.dispatchEvent(event);
    });
    this.addEventListener("mousemove", (evt) => {
      const detail = this.calcDetailForEvent(evt, "mousemove");
      const event = new CustomEvent(
        SEIS_MOVE_EVENT,
        {
          detail,
          bubbles: true,
          cancelable: false,
          composed: true
        }
      );
      this.dispatchEvent(event);
    });
  }
  get seismographConfig() {
    return super.seismographConfig;
  }
  set seismographConfig(seismographConfig) {
    if (isDef(this.seismographConfig.linkedTimeScale)) {
      this.seismographConfig.linkedTimeScale.unlink(this.time_scalable);
    }
    if (this.seismographConfig.linkedAmplitudeScale) {
      this.seismographConfig.linkedAmplitudeScale.unlink(this.amp_scalable);
    }
    super.seismographConfig = seismographConfig;
    if (isDef(this.seismographConfig.linkedTimeScale)) {
      this.seismographConfig.linkedTimeScale.link(this.time_scalable);
    }
    if (this.seismographConfig.linkedAmplitudeScale) {
      this.seismographConfig.linkedAmplitudeScale.link(this.amp_scalable);
    }
    this.redraw();
  }
  connectedCallback() {
    if (this.seismographConfig.linkedAmplitudeScale) {
      this.beforeFirstDraw = false;
      this.seismographConfig.linkedAmplitudeScale.recalculate().catch((e) => warn(e));
    } else {
      this.redraw();
    }
  }
  disconnectedCallback() {
    if (this.seismographConfig.linkedAmplitudeScale) {
      this.seismographConfig.linkedAmplitudeScale.unlink(this.amp_scalable);
    }
    if (this.seismographConfig.linkedTimeScale) {
      this.seismographConfig.linkedTimeScale.unlink(this.time_scalable);
    }
  }
  attributeChangedCallback(_name, _oldValue, _newValue) {
    this.redraw();
  }
  checkResize() {
    const wrapper = this.getShadowRoot().querySelector("div");
    const svgEl = wrapper.querySelector("svg");
    const rect = svgEl.getBoundingClientRect();
    if (rect.width !== this.outerWidth || rect.height !== this.outerHeight) {
      return true;
    }
    return false;
  }
  draw() {
    if (!this.isConnected) {
      return;
    }
    if (this.panZoomer && this.seismographConfig.linkedTimeScale) {
      this.panZoomer.linkedTimeScale = this.seismographConfig.linkedTimeScale;
      this.panZoomer.wheelZoom = this.seismographConfig.wheelZoom;
    }
    const wrapper = this.getShadowRoot().querySelector("div");
    const svgEl = wrapper.querySelector("svg");
    const rect = svgEl.getBoundingClientRect();
    if (rect.width === 0 || rect.height === 0) {
      log(
        `Attempt draw seismograph, but width/height too small: ${rect.width} ${rect.height}`
      );
      return;
    }
    let calcHeight = rect.height;
    if (rect.width !== this.outerWidth || rect.height !== this.outerHeight) {
      if (isNumArg(this.seismographConfig.minHeight) && calcHeight < this.seismographConfig.minHeight) {
        calcHeight = this.seismographConfig.minHeight;
      }
      if (isNumArg(this.seismographConfig.maxHeight) && calcHeight > this.seismographConfig.maxHeight) {
        calcHeight = this.seismographConfig.maxHeight;
      }
    }
    this.calcWidthHeight(rect.width, calcHeight);
    this.g.attr(
      "transform",
      `translate(${this.seismographConfig.margin.left}, ${this.seismographConfig.margin.top} )`
    );
    if (this.canvas && this.canvasHolder) {
      this.canvasHolder.attr("width", this.width).attr("height", this.height);
      this.canvasHolder.attr("x", this.seismographConfig.margin.left);
      this.canvasHolder.attr("y", this.seismographConfig.margin.top);
      this.canvas.attr("width", this.seismographConfig.resolutionScale * this.width).attr("height", this.seismographConfig.resolutionScale * this.height);
      this.canvas.attr("style", `width: ${this.width}px; height: ${this.height}px;`);
    } else {
      const svg = select_default2(svgEl);
      this.canvasHolder = svg.insert("foreignObject", ":first-child").classed("seismograph", true).attr("x", this.seismographConfig.margin.left).attr("y", this.seismographConfig.margin.top).attr("width", this.width).attr("height", this.height);
      if (this.canvasHolder == null) {
        throw new Error("canvasHolder is null");
      }
      const c = this.canvasHolder.append("xhtml:canvas").classed("seismograph", true).attr("xmlns", XHTML_NS).attr("x", 0).attr("y", 0).attr("width", this.seismographConfig.resolutionScale * this.width).attr("height", this.seismographConfig.resolutionScale * this.height).attr("style", `width: ${this.width}px; height: ${this.height}px;`);
      this.canvas = c;
      if (this.seismographConfig.linkedTimeScale) {
        const canvasHolderNode = this.canvasHolder.node();
        if (!this.panZoomer && canvasHolderNode) {
          this.panZoomer = new PanZoomer(canvasHolderNode, this.seismographConfig.linkedTimeScale, this.seismographConfig.wheelZoom);
        } else if (this.panZoomer && canvasHolderNode) {
          this.panZoomer.target = canvasHolderNode;
        }
      }
    }
    this.drawSeismograms();
    this.drawAxis();
    const unitsLabel = this.seismographConfig.ySublabelIsUnits ? this.createUnitsLabel() : "";
    drawAxisLabels(
      svgEl,
      this.seismographConfig,
      this.height,
      this.width,
      this.createHandlebarsInput(),
      unitsLabel
    );
    if (this.seismographConfig.doMarkers) {
      this.drawMarkers();
    }
    this.beforeFirstDraw = false;
  }
  printSizes() {
    const wrapper = this.getShadowRoot().querySelector("div");
    const svgEl = wrapper.querySelector("svg");
    let out = "";
    const rect = svgEl.getBoundingClientRect();
    out += "svg rect.height " + rect.height + "\n";
    out += "svg rect.width " + rect.width + "\n";
    const grect = this.getBoundingClientRect();
    out += "parent rect.height " + grect.height + "\n";
    out += "parent rect.width " + grect.width + "\n";
    const cnode = this.canvas?.node();
    const crect = cnode?.getBoundingClientRect();
    if (this.canvas && cnode && crect) {
      out += "c rect.height " + crect.height + "\n";
      out += "c rect.width " + crect.width + "\n";
      out += "c style.height " + this.canvas.style("height") + "\n";
      out += "c style.width " + this.canvas.style("width") + "\n";
      out += "this.height " + this.height + "\n";
      out += "this.width " + this.width + "\n";
      out += "canvas.height " + cnode.height + "\n";
      out += "canvas.width " + cnode.width + "\n";
      out += "this.outerHeight " + this.outerHeight + "\n";
      out += "this.outerWidth " + this.outerWidth + "\n";
      const m = this.seismographConfig.margin;
      out += m ? `this.margin ${String(m)}
` : `this.margin null
`;
    } else {
      out += "crect bounding rect is null\n";
    }
    log(out);
  }
  calcDetailForEvent(evt, _type) {
    const margin = this.seismographConfig.margin;
    const mouseTimeVal = this.timeScaleForAxis().invert(
      evt.offsetX - margin.left
    );
    const mouseAmp = this.ampScaleForAxis().invert(evt.offsetY - margin.top);
    const out = {
      mouseevent: evt,
      time: null,
      relative_time: null,
      amplitude: mouseAmp,
      seismograph: this
    };
    if (mouseTimeVal instanceof DateTime) {
      out.time = mouseTimeVal;
    } else {
      out.relative_time = Duration.fromMillis(mouseTimeVal * 1e3);
    }
    return out;
  }
  isVisible() {
    const elem = this.canvas?.node();
    if (!elem) {
      return false;
    }
    return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
  }
  drawSeismograms() {
    if (!this.isVisible()) {
      return;
    }
    const canvas = this.canvas?.node();
    if (!canvas) {
      return;
    }
    clearCanvas(canvas);
    if (this.seismographConfig.xGridLines) {
      drawXScaleGridLines(
        canvas,
        this.timeScaleForAxis(),
        this.seismographConfig.gridLineColor
      );
    }
    if (this.seismographConfig.yGridLines) {
      drawYScaleGridLines(
        canvas,
        this.ampScaleForAxis(),
        this.seismographConfig.gridLineColor
      );
    }
    drawAllOnCanvas(
      canvas,
      this._seisDataList,
      this._seisDataList.map((sdd) => this.timeScaleForSeisDisplayData(sdd, true)),
      // Set resolution scaling to true
      this._seisDataList.map((sdd) => this.ampScaleForSeisDisplayData(sdd)),
      this._seisDataList.map(
        (_sdd, ti) => this.seismographConfig.getColorForIndex(ti)
      ),
      this.seismographConfig.lineWidth * this.seismographConfig.resolutionScale,
      this.seismographConfig.connectSegments,
      this.minmax_sample_pixels
    );
  }
  calcScaleAndZoom() {
    this.rescaleYAxis();
    const container = this.svg.select("defs").select("#" + CLIP_PREFIX + this.plotId);
    if (container.empty()) {
      this.svg.append("defs").append("clipPath").attr("id", CLIP_PREFIX + this.plotId);
    }
    const clip = this.svg.select("defs").select("#" + CLIP_PREFIX + this.plotId);
    clip.selectAll("rect").remove();
    clip.append("rect").attr("width", this.width).attr("height", this.height);
  }
  ampScaleForSeisDisplayData(sdd) {
    const ampScale = this.__initAmpScale(true);
    if (this.seismographConfig.linkedAmplitudeScale) {
      const drawHalfWidth = this.amp_scalable.drawHalfWidth;
      let sensitivityVal = 1;
      if (this.seismographConfig.doGain && sdd.seismogram?.isYUnitCount() && sdd.sensitivity?.sensitivity) {
        sensitivityVal = sdd.sensitivity.sensitivity;
      }
      if (!this.seismographConfig.isCenteredAmp()) {
        return ampScale.domain([
          (this.amp_scalable.drawMiddle - drawHalfWidth) * sensitivityVal,
          (this.amp_scalable.drawMiddle + drawHalfWidth) * sensitivityVal
        ]);
      }
      const sddInterval = this.displayTimeRangeForSeisDisplayData(sdd);
      const minMax = calcMinMax(
        sdd,
        sddInterval,
        false,
        this.seismographConfig.amplitudeMode
      );
      if (minMax) {
        const myMin = minMax.middle - drawHalfWidth * sensitivityVal;
        const myMax = minMax.middle + drawHalfWidth * sensitivityVal;
        ampScale.domain([myMin, myMax]);
      } else {
        ampScale.domain([-1, 1]);
      }
    } else if (this.seismographConfig.fixedAmplitudeScale) {
      ampScale.domain(this.seismographConfig.fixedAmplitudeScale);
    } else {
      throw new Error(
        "ampScaleForSeisDisplayData Must be either linked or fixed amp scale"
      );
    }
    return ampScale;
  }
  displayTimeRangeForSeisDisplayData(sdd) {
    let plotInterval;
    if (this.seismographConfig.linkedTimeScale) {
      if (this.time_scalable.drawDuration.equals(ZERO_DURATION)) {
        this.seismographConfig.linkedTimeScale.recalculate().catch((m) => {
          console.warn(
            `problem recalc displayTimeRangeForSeisDisplayData: ${m}`
          );
        });
      }
      const startOffset = this.time_scalable.drawAlignmentTimeOffset;
      const duration3 = this.time_scalable.drawDuration;
      plotInterval = sdd.relativeTimeWindow(startOffset, duration3);
    } else if (this.seismographConfig.fixedTimeScale) {
      plotInterval = this.seismographConfig.fixedTimeScale;
    } else {
      throw new Error("Must be either fixed or linked time scale");
    }
    return plotInterval;
  }
  timeScaleForSeisDisplayData(sdd, scaleForResolution = false) {
    let plotInterval;
    if (sdd) {
      if (sdd instanceof SeismogramDisplayData) {
        plotInterval = this.displayTimeRangeForSeisDisplayData(sdd);
      } else {
        plotInterval = sdd;
      }
    } else {
      if (this.seismographConfig.linkedTimeScale) {
        plotInterval = durationEnd(
          this.seismographConfig.linkedTimeScale.duration,
          DateTime.utc()
        );
      } else if (this.seismographConfig.fixedTimeScale) {
        plotInterval = this.seismographConfig.fixedTimeScale;
      } else {
        plotInterval = durationEnd(1, DateTime.utc());
      }
    }
    return new LuxonTimeScale(
      plotInterval,
      [0, scaleForResolution ? this.seismographConfig.resolutionScale * this.width : this.width]
    );
  }
  /**
   * Draws the top, bottom, (time) axis and the left and right (amplitude) axis if configured.
   */
  drawAxis() {
    this.drawTopBottomAxis();
    this.drawLeftRightAxis();
  }
  /**
   * Creates amp scale, set range based on height.
   * @private
   * @returns amp scale with range set
   */
  __initAmpScale(scaleForResolution = false) {
    const ampAxisScale = linear2();
    const height = (scaleForResolution ? this.seismographConfig.resolutionScale * this.height : this.height) - 1;
    ampAxisScale.range([height, 1]);
    return ampAxisScale;
  }
  ampScaleForAxis() {
    const ampAxisScale = this.__initAmpScale();
    if (this.seismographConfig.fixedAmplitudeScale) {
      ampAxisScale.domain(this.seismographConfig.fixedAmplitudeScale);
    } else if (this.seismographConfig.linkedAmplitudeScale) {
      let middle;
      if (this.seismographConfig.isCenteredAmp()) {
        middle = 0;
      } else {
        middle = this.amp_scalable.drawMiddle;
      }
      ampAxisScale.domain([
        middle - this.amp_scalable.drawHalfWidth,
        middle + this.amp_scalable.drawHalfWidth
      ]);
    } else {
      throw new Error(
        "ampScaleForAxis Must be either linked or fixed amp scale"
      );
    }
    return ampAxisScale;
  }
  timeScaleForAxis() {
    let xScaleToDraw;
    if (this.seismographConfig.isRelativeTime) {
      xScaleToDraw = linear2();
      xScaleToDraw.range([0, this.width]);
      if (this.seismographConfig.linkedTimeScale) {
        const startOffset = this.time_scalable.drawAlignmentTimeOffset.toMillis() / 1e3;
        const duration3 = this.time_scalable.drawDuration.toMillis() / 1e3;
        if (duration3 > 0) {
          xScaleToDraw.domain([startOffset, startOffset + duration3]);
        } else {
          xScaleToDraw.domain([startOffset + duration3, startOffset]);
        }
      } else if (this.seismographConfig.fixedTimeScale) {
        const psed = this.seismographConfig.fixedTimeScale;
        const s2 = validStartTime(psed);
        const e = validEndTime(psed);
        xScaleToDraw.domain([s2.toMillis() / 1e3, e.toMillis() / 1e3]);
      } else {
        throw new Error("neither fixed nor linked time scale");
      }
    } else {
      if (this.seismographConfig.linkedTimeScale) {
        if (this.seisData.length > 0) {
          xScaleToDraw = this.timeScaleForSeisDisplayData(this.seisData[0]);
        } else {
          xScaleToDraw = this.timeScaleForSeisDisplayData();
        }
      } else if (this.seismographConfig.fixedTimeScale) {
        const psed = this.seismographConfig.fixedTimeScale;
        xScaleToDraw = this.timeScaleForSeisDisplayData(psed);
      } else {
        throw new Error("neither fixed nor linked time scale");
      }
    }
    return xScaleToDraw;
  }
  /**
   * Draws the left and right (amplitude) axis if configured.
   *
   */
  drawTopBottomAxis() {
    this.g.selectAll("g.axis--x").remove();
    this.g.selectAll("g.axis--x-top").remove();
    let xScaleToDraw = this.timeScaleForAxis();
    if (this.seismographConfig.isRelativeTime) {
      xScaleToDraw = xScaleToDraw;
      if (this.seismographConfig.isXAxis) {
        const xAxis = axisBottom(xScaleToDraw);
        xAxis.tickFormat(
          createNumberFormatWrapper(this.seismographConfig.relativeTimeFormat)
        );
        this.g.append("g").attr("class", "axis axis--x").attr("transform", "translate(0," + this.height + ")").call(xAxis);
      }
      if (this.seismographConfig.isXAxisTop) {
        const xAxisTop = axisTop(xScaleToDraw);
        xAxisTop.tickFormat(
          createNumberFormatWrapper(this.seismographConfig.relativeTimeFormat)
        );
        this.g.append("g").attr("class", "axis axis--x-top").call(xAxisTop);
      }
    } else {
      xScaleToDraw = xScaleToDraw;
      if (this.seismographConfig.isXAxis) {
        const xAxis = axisBottom(xScaleToDraw.d3scale);
        xAxis.tickFormat(
          createDateFormatWrapper(this.seismographConfig.timeFormat)
        );
        this.g.append("g").attr("class", "axis axis--x").attr("transform", "translate(0," + this.height + ")").call(xAxis);
      }
      if (this.seismographConfig.isXAxisTop) {
        const xAxisTop = axisTop(xScaleToDraw.d3scale);
        xAxisTop.tickFormat(
          createDateFormatWrapper(this.seismographConfig.timeFormat)
        );
        this.g.append("g").attr("class", "axis axis--x-top").call(xAxisTop);
      }
    }
  }
  /**
   * Draws the left and right (amplitude) axis if configured.
   */
  drawLeftRightAxis() {
    this.g.selectAll("g.axis--y").remove();
    this.g.selectAll("g.axis--y-right").remove();
    const [yAxis, yAxisRight] = this.createLeftRightAxis();
    if (isDef(yAxis)) {
      this.g.append("g").attr("class", "axis axis--y").call(yAxis);
    }
    if (isDef(yAxisRight)) {
      this.g.append("g").attr("class", "axis axis--y-right").attr("transform", "translate(" + this.width + ",0)").call(yAxisRight);
    }
  }
  createLeftRightAxis() {
    let yAxis = null;
    let yAxisRight = null;
    const axisScale = this.ampScaleForAxis();
    if (this.seismographConfig.isYAxis) {
      yAxis = axisLeft(axisScale).tickFormat(
        numberFormatWrapper(this.seismographConfig.amplitudeFormat)
      );
      yAxis.scale(axisScale);
      yAxis.ticks(
        this.seismographConfig.yAxisNumTickHint,
        this.seismographConfig.amplitudeFormat
      );
    }
    if (this.seismographConfig.isYAxisRight) {
      yAxisRight = axisRight(axisScale).tickFormat(
        numberFormatWrapper(this.seismographConfig.amplitudeFormat)
      );
      yAxisRight.scale(axisScale);
      yAxisRight.ticks(this.seismographConfig.yAxisNumTickHint, this.seismographConfig.amplitudeFormat);
    }
    return [yAxis, yAxisRight];
  }
  rescaleYAxis() {
    if (!this.beforeFirstDraw) {
      const delay = 500;
      if (this.throttleRescale) {
        clearTimeout(this.throttleRescale);
      }
      this.throttleRescale = setTimeout(() => {
        const [yAxis, yAxisRight] = this.createLeftRightAxis();
        if (yAxis) {
          this.g.select(".axis--y").transition().duration(delay / 2).call(yAxis);
        }
        if (yAxisRight) {
          this.g.select(".axis--y-right").transition().duration(delay / 2).call(yAxisRight);
        }
        this.throttleRescale = null;
      }, delay);
    }
  }
  createHandlebarsInput() {
    return {
      seisDataList: this._seisDataList,
      seisConfig: this._seismographConfig
    };
  }
  drawAxisLabels() {
    this.drawTitle();
    this.drawXLabel();
    this.drawXSublabel();
    this.drawYLabel();
    this.drawYSublabel();
  }
  resetZoom() {
    if (this.seismographConfig.linkedTimeScale) {
      this.seismographConfig.linkedTimeScale.unzoom();
    } else {
      throw new Error("can't reset zoom for fixedTimeScale");
    }
  }
  redrawWithXScale() {
    const mythis = this;
    if (!this.beforeFirstDraw) {
      this.g.select("g.allseismograms").selectAll("g.seismogram").remove();
      if (this.seismographConfig.windowAmp) {
        this.recheckAmpScaleDomain();
      }
      this.drawSeismograms();
      this.g.select("g.allmarkers").selectAll("g.marker").attr("transform", function(v) {
        const mh = v;
        mh.xscale = mythis.timeScaleForSeisDisplayData(mh.sdd);
        const textx = mh.xscale.for(mh.marker.time);
        return "translate(" + textx + ",0)";
      });
      this.g.select("g.allmarkers").selectAll("g.markertext").attr("transform", function() {
        const axisScale = mythis.ampScaleForAxis();
        const maxY = axisScale.range()[0];
        const deltaY = axisScale.range()[0] - axisScale.range()[1];
        const texty = maxY - mythis.seismographConfig.markerTextOffset * deltaY;
        return "translate(0," + texty + ") rotate(" + mythis.seismographConfig.markerTextAngle + ")";
      });
      const undrawnMarkers = this._seisDataList.reduce((acc, sdd) => {
        const sddXScale = this.timeScaleForSeisDisplayData(sdd);
        sdd.markerList.forEach(
          (m) => acc.push({
            // use marker holder to also hold xscale in case relative plot
            marker: m,
            sdd,
            xscale: sddXScale
          })
        );
        return acc;
      }, new Array(0)).filter((mh) => {
        const xpixel = mh.xscale.for(mh.marker.time);
        return xpixel >= mh.xscale.range[0] && xpixel <= mh.xscale.range[1];
      });
      if (this.seismographConfig.doMarkers && undrawnMarkers.length !== 0) {
        this.drawMarkers();
      }
      this.drawTopBottomAxis();
    }
  }
  drawMarkers() {
    const axisScale = this.ampScaleForAxis();
    const allMarkers = this._seisDataList.reduce((acc, sdd) => {
      const sddXScale = this.timeScaleForSeisDisplayData(sdd);
      sdd.markerList.forEach(
        (m) => acc.push({
          // use marker holder to also hold xscale in case relative plot
          marker: m,
          sdd,
          xscale: sddXScale
        })
      );
      return acc;
    }, []).filter((mh) => {
      const xpixel = mh.xscale.for(mh.marker.time);
      return xpixel >= mh.xscale.range[0] && xpixel <= mh.xscale.range[1];
    });
    const mythis = this;
    const markerG = this.g.select("g.allmarkers");
    markerG.selectAll("g.marker").remove();
    const labelSelection = markerG.selectAll("g.marker").data(allMarkers, function(v) {
      const mh = v;
      return `${mh.marker.name}_${mh.marker.time.toISO()}`;
    });
    labelSelection.exit().remove();
    const radianTextAngle = this.seismographConfig.markerTextAngle * Math.PI / 180;
    labelSelection.enter().append("g").classed("marker", true).attr("transform", function(v) {
      const mh = v;
      const textx = mh.xscale.for(mh.marker.time);
      return "translate(" + textx + ",0)";
    }).each(function(mh) {
      const drawG = select_default2(this);
      drawG.classed(mh.marker.name, true).classed(mh.marker.markertype, true);
      const innerTextG = drawG.append("g").attr("class", "markertext").attr("transform", () => {
        const maxY = axisScale.range()[0];
        const deltaY = axisScale.range()[0] - axisScale.range()[1];
        const texty = maxY - mythis.seismographConfig.markerTextOffset * deltaY;
        return "translate(0," + texty + ") rotate(" + mythis.seismographConfig.markerTextAngle + ")";
      });
      innerTextG.append("title").text(() => {
        if (mh.marker.description) {
          return mh.marker.description;
        } else {
          return mh.marker.markertype + " " + mh.marker.name + " " + mh.marker.time.toISO();
        }
      });
      const textSel = innerTextG.append("text");
      if (mh.marker.link && mh.marker.link.length > 0) {
        textSel.append("svg:a").attr("xlink:href", () => "" + mh.marker.link).text(function(datum2) {
          const mh2 = datum2;
          return mh2.marker.name;
        });
      } else {
        textSel.text(function(datum2) {
          const mh2 = datum2;
          return mh2.marker.name;
        });
      }
      textSel.attr("dy", "-0.35em").call(function(selection2) {
        selection2.each(function(datum2) {
          const mh2 = datum2;
          mh2.bbox = {
            height: 15,
            width: 20
          };
          try {
            mh2.bbox = this.getBBox();
          } catch (error51) {
            console.warn(error51);
          }
        });
      });
      innerTextG.insert("polygon", "text").attr("points", function(datum2) {
        const mh2 = datum2;
        let bboxH = 10 + 5;
        let bboxW = 10;
        if (mh2.bbox) {
          bboxH = mh2.bbox.height + 5;
          bboxW = mh2.bbox.width;
        }
        return "0,0 " + -1 * bboxH * Math.tan(radianTextAngle) + ",-" + bboxH + " " + bboxW + ",-" + bboxH + " " + bboxW + ",0";
      });
      let markerPoleY;
      if (mythis.seismographConfig.markerFlagpoleBase === "none") {
        markerPoleY = 0;
      } else if (mythis.seismographConfig.markerFlagpoleBase === "short") {
        markerPoleY = (axisScale.range()[0] + axisScale.range()[1]) / 4;
      } else if (mythis.seismographConfig.markerFlagpoleBase === "center") {
        markerPoleY = (axisScale.range()[0] + axisScale.range()[1]) / 2;
      } else {
        markerPoleY = axisScale.range()[0];
      }
      const markerPole = `M0,0l0,${markerPoleY}`;
      drawG.append("path").classed("markerpath", true).attr("d", markerPole);
    });
  }
  calcWidthHeight(nOuterWidth, nOuterHeight) {
    if (nOuterWidth < this.seismographConfig.margin.left + this.seismographConfig.margin.right) {
      throw new Error(
        `width too small for margin: ${nOuterWidth} < ${this.seismographConfig.margin.left} + ${this.seismographConfig.margin.right}`
      );
    }
    if (nOuterHeight < this.seismographConfig.margin.top + this.seismographConfig.margin.bottom) {
      throw new Error(
        `height too small for margin: ${nOuterHeight} < ${this.seismographConfig.margin.top} + ${this.seismographConfig.margin.bottom}`
      );
    }
    this.outerWidth = nOuterWidth;
    this.outerHeight = nOuterHeight;
    this.height = this.outerHeight - this.seismographConfig.margin.top - this.seismographConfig.margin.bottom;
    this.width = this.outerWidth - this.seismographConfig.margin.left - this.seismographConfig.margin.right;
    this.calcScaleAndZoom();
    if (this.canvasHolder) {
      this.canvasHolder.attr("width", this.width).attr("height", this.height + 1);
    }
    if (this.canvas) {
      this.canvas.attr("width", this.seismographConfig.resolutionScale * this.width).attr("height", this.seismographConfig.resolutionScale * this.height + 1);
    }
    if (this.panZoomer) {
      this.panZoomer.width = this.width;
    }
  }
  drawTitle() {
    const wrapper = this.getShadowRoot().querySelector("div");
    const isTitleCSS = getComputedStyle(wrapper).getPropertyValue("--sp-seismograph-is-title");
    const svgEl = wrapper.querySelector("svg");
    if (isTitleCSS === "0") {
      removeTitle(svgEl);
    } else {
      drawTitle(
        svgEl,
        this.seismographConfig,
        this.height,
        this.width,
        this.createHandlebarsInput()
      );
    }
  }
  drawXLabel() {
    const wrapper = this.getShadowRoot().querySelector("div");
    const isXLabelCSS = getComputedStyle(wrapper).getPropertyValue("--sp-seismograph-is-xlabel");
    const svgEl = wrapper.querySelector("svg");
    if (isXLabelCSS === "0") {
      removeXLabel(svgEl);
    } else {
      drawXLabel(
        svgEl,
        this.seismographConfig,
        this.height,
        this.width,
        this.createHandlebarsInput()
      );
    }
  }
  drawXSublabel() {
    const wrapper = this.getShadowRoot().querySelector("div");
    const isXSublabelCSS = getComputedStyle(wrapper).getPropertyValue("--sp-seismograph-is-xsublabel");
    const svgEl = wrapper.querySelector("svg");
    if (isXSublabelCSS === "0") {
      removeXSublabel(svgEl);
    } else {
      drawXSublabel(
        svgEl,
        this.seismographConfig,
        this.height,
        this.width,
        this.createHandlebarsInput()
      );
    }
  }
  drawYLabel() {
    const wrapper = this.getShadowRoot().querySelector("div");
    const isYLabelCSS = getComputedStyle(wrapper).getPropertyValue("--sp-seismograph-is-ylabel");
    const svgEl = wrapper.querySelector("svg");
    if (isYLabelCSS === "0") {
      removeYLabel(svgEl);
    } else {
      drawYLabel(
        svgEl,
        this.seismographConfig,
        this.height,
        this.width,
        this.createHandlebarsInput()
      );
    }
  }
  drawYSublabel() {
    const wrapper = this.getShadowRoot().querySelector("div");
    const isYSublabelCSS = getComputedStyle(wrapper).getPropertyValue("--sp-seismograph-is-ysublabel");
    const svgEl = wrapper.querySelector("svg");
    if (isYSublabelCSS === "0") {
      removeYSublabel(svgEl);
    } else {
      const unitsLabel = this.seismographConfig.ySublabelIsUnits ? this.createUnitsLabel() : "";
      drawYSublabel(
        svgEl,
        this.seismographConfig,
        this.height,
        this.width,
        this.createHandlebarsInput(),
        unitsLabel
      );
    }
  }
  /**
   * Update the duration if not already set. This only matters for
   * linedTimeScale currently.
   */
  calcTimeScaleDomain() {
    if (isDef(this.seismographConfig.linkedTimeScale)) {
      const linkedTimeScale = this.seismographConfig.linkedTimeScale;
      if (this._seisDataList.length !== 0 && linkedTimeScale.duration.toMillis() === 0) {
        this.seismographConfig.linkedTimeScale.duration = findMaxDuration(
          this._seisDataList
        );
      }
    }
  }
  /**
   * Calculate the amplitude range over the current time range, depending
   * on amplitude style.
   *
   * @returns min max over the time range
   */
  calcAmpScaleDomain() {
    let minMax;
    if (this.seismographConfig.fixedAmplitudeScale) {
      minMax = MinMaxable.fromArray(this.seismographConfig.fixedAmplitudeScale);
    } else {
      if (this.seismographConfig.windowAmp) {
        if (isDef(this.seismographConfig.linkedTimeScale)) {
          minMax = findMinMaxOverRelativeTimeRange(
            this._seisDataList,
            this.seismographConfig.linkedTimeScale.offset,
            this.seismographConfig.linkedTimeScale.duration,
            this.seismographConfig.doGain,
            this.seismographConfig.amplitudeMode
          );
        } else if (isDef(this.seismographConfig.fixedTimeScale)) {
          minMax = findMinMaxOverTimeRange(
            this._seisDataList,
            this.seismographConfig.fixedTimeScale,
            this.seismographConfig.doGain,
            this.seismographConfig.amplitudeMode
          );
        } else {
          throw new Error("neither fixed nor linked time scale");
        }
      } else {
        minMax = findMinMax(
          this._seisDataList,
          this.seismographConfig.doGain,
          this.seismographConfig.amplitudeMode
        );
      }
      if (minMax.halfWidth === 0) {
      }
      if (this.seismographConfig.isYAxisNice) {
        let scale = linear2();
        scale.domain(minMax.asArray());
        scale = scale.nice();
        minMax = MinMaxable.fromArray(scale.domain());
      }
    }
    return minMax;
  }
  recheckAmpScaleDomain() {
    const calcMidHW = this.calcAmpScaleDomain();
    const oldMiddle = this.amp_scalable.middle;
    const oldHalfWidth = this.amp_scalable.halfWidth;
    this.amp_scalable.minMax = calcMidHW;
    if (this.seismographConfig.linkedAmplitudeScale) {
      if (this.amp_scalable.middle !== oldMiddle || this.amp_scalable.halfWidth !== oldHalfWidth) {
        this.seismographConfig.linkedAmplitudeScale.recalculate().catch((m) => {
          console.warn(`problem recalc amp scale: ${m}`);
        });
      }
    } else {
      this.redoDisplayYScale();
    }
  }
  redoDisplayYScale() {
    this.rescaleYAxis();
    if (this.seismographConfig.ySublabelIsUnits) {
      this.drawYSublabel();
    }
  }
  createUnitsLabel() {
    let ySublabel = "";
    if (this.seismographConfig.doGain && this._seisDataList.length > 0 && this._seisDataList.every((sdd) => sdd.hasSensitivity()) && this._seisDataList.every(
      (sdd) => isDef(sdd.seismogram) && sdd.seismogram.yUnit === COUNT_UNIT2
    )) {
      const firstSensitivity = this._seisDataList[0].sensitivity;
      const allSameUnits = firstSensitivity && this._seisDataList.every(
        (sdd) => isDef(firstSensitivity) && sdd.sensitivity && firstSensitivity.inputUnits === sdd.sensitivity.inputUnits
      );
      if (this.seismographConfig.ySublabelIsUnits) {
        const unitList = this._seisDataList.map(
          (sdd) => sdd.sensitivity ? sdd.sensitivity.inputUnits : "uknown"
        ).join(",");
        if (!allSameUnits) {
          ySublabel = unitList;
        } else {
          ySublabel = firstSensitivity.inputUnits;
        }
      }
    } else {
      if (this.seismographConfig.ySublabelIsUnits) {
        const allUnits = [];
        for (const t of this._seisDataList) {
          if (t.seismogram) {
            const u = t.seismogram.yUnit;
            allUnits.push(u);
          }
        }
        if (allUnits.length === 0) {
          allUnits.push("Count");
        }
        ySublabel = allUnits.join(" ");
      }
    }
    if (this.seismographConfig.ySublabelIsUnits && this.seismographConfig.isCenteredAmp()) {
      ySublabel = `centered ${ySublabel}`;
    }
    return ySublabel;
  }
  getSeismogramData() {
    return this._seisDataList;
  }
  /**
   * Notification to the element that something about the current seismogram
   * data has changed. This could be that the actual waveform data has been updated
   * or that auxillary data like quake or channel has been added. This should
   * trigger a redraw.
   */
  seisDataUpdated() {
    this.calcTimeScaleDomain();
    this.recheckAmpScaleDomain();
    if (!this.beforeFirstDraw) {
      if (this.seismographConfig.linkedAmplitudeScale) {
        this.seismographConfig.linkedAmplitudeScale.recalculate().catch((e) => warn(e));
      } else {
        this.redraw();
      }
    }
  }
  /**
   * Finds the SeismogramDisplayData within the display containing the given
   * Seismogram.
   *
   * @param   seis seismogram to search for
   * @returns       SeismogramDisplayData if found or null if not
   */
  getDisplayDataForSeismogram(seis) {
    const out = this._seisDataList.find((sd) => sd.seismogram === seis);
    if (out) {
      return out;
    } else {
      return null;
    }
  }
  /**
   * Removes a seismogram from the display.
   *
   * @param   seisData seis data to remove
   */
  removeSeisData(seisData) {
    this._seisDataList = this._seisDataList.filter((sd) => sd !== seisData);
  }
  /**
   * Removes seismograms that do not overlap the window.
   *
   * @param   timeRange overlap data to keep
   */
  trim(timeRange) {
    if (this._seisDataList) {
      this._seisDataList = this._seisDataList.filter(function(d) {
        return d.timeRange.overlaps(timeRange);
      });
      if (this._seisDataList.length > 0) {
        this.recheckAmpScaleDomain();
        this.drawSeismograms();
      }
    }
  }
};
var SeismographAmplitudeScalable = class extends AmplitudeScalable {
  constructor(graph) {
    const calcMidHW = graph.calcAmpScaleDomain();
    super(calcMidHW);
    this.graph = graph;
    this.drawHalfWidth = super.halfWidth;
    this.drawMiddle = super.middle;
  }
  notifyAmplitudeChange(middle, halfWidth) {
    if (middle !== this.drawMiddle || halfWidth !== this.drawHalfWidth) {
      this.drawMiddle = middle;
      this.drawHalfWidth = halfWidth;
      this.graph.redoDisplayYScale();
      if (!this.graph.beforeFirstDraw) {
        this.graph.redraw();
      }
    }
  }
};
var ZERO_DURATION = Duration.fromMillis(0);
var SeismographTimeScalable = class extends TimeScalable {
  constructor(graph, alignmentTimeOffset, duration3) {
    super(alignmentTimeOffset, duration3);
    this.graph = graph;
    this.drawAlignmentTimeOffset = ZERO_DURATION;
    this.drawDuration = ZERO_DURATION;
  }
  notifyTimeRangeChange(offset2, duration3) {
    if (!this.drawAlignmentTimeOffset.equals(offset2) || !this.drawDuration.equals(duration3)) {
      this.drawAlignmentTimeOffset = offset2;
      this.drawDuration = duration3;
      if (isDef(this.graph) && !this.graph.beforeFirstDraw) {
        window.requestAnimationFrame(() => {
          this.graph.redrawWithXScale();
        });
      }
    }
  }
};
Seismograph._lastID = 0;
function createNumberFormatWrapper(formatter) {
  return (nValue) => {
    if (typeof nValue === "number") {
      return formatter(nValue);
    } else {
      return formatter(nValue.valueOf());
    }
  };
}
function createDateFormatWrapper(formatter) {
  return (nValue) => {
    if (nValue instanceof Date) {
      return formatter(nValue);
    } else if (typeof nValue === "number") {
      return formatter(new Date(nValue));
    } else {
      return formatter(new Date(nValue.valueOf()));
    }
  };
}
customElements.define(SEISMOGRAPH_ELEMENT, Seismograph);

// node_modules/d3-shape/src/constant.js
function constant_default3(x2) {
  return function constant() {
    return x2;
  };
}

// node_modules/d3-path/src/path.js
var pi = Math.PI;
var tau = 2 * pi;
var epsilon2 = 1e-6;
var tauEpsilon = tau - epsilon2;
function append(strings) {
  this._ += strings[0];
  for (let i = 1, n2 = strings.length; i < n2; ++i) {
    this._ += arguments[i] + strings[i];
  }
}
function appendRound(digits) {
  let d = Math.floor(digits);
  if (!(d >= 0)) throw new Error(`invalid digits: ${digits}`);
  if (d > 15) return append;
  const k = 10 ** d;
  return function(strings) {
    this._ += strings[0];
    for (let i = 1, n2 = strings.length; i < n2; ++i) {
      this._ += Math.round(arguments[i] * k) / k + strings[i];
    }
  };
}
var Path = class {
  constructor(digits) {
    this._x0 = this._y0 = // start of current subpath
    this._x1 = this._y1 = null;
    this._ = "";
    this._append = digits == null ? append : appendRound(digits);
  }
  moveTo(x2, y2) {
    this._append`M${this._x0 = this._x1 = +x2},${this._y0 = this._y1 = +y2}`;
  }
  closePath() {
    if (this._x1 !== null) {
      this._x1 = this._x0, this._y1 = this._y0;
      this._append`Z`;
    }
  }
  lineTo(x2, y2) {
    this._append`L${this._x1 = +x2},${this._y1 = +y2}`;
  }
  quadraticCurveTo(x1, y1, x2, y2) {
    this._append`Q${+x1},${+y1},${this._x1 = +x2},${this._y1 = +y2}`;
  }
  bezierCurveTo(x1, y1, x2, y2, x3, y3) {
    this._append`C${+x1},${+y1},${+x2},${+y2},${this._x1 = +x3},${this._y1 = +y3}`;
  }
  arcTo(x1, y1, x2, y2, r) {
    x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
    if (r < 0) throw new Error(`negative radius: ${r}`);
    let 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 (this._x1 === null) {
      this._append`M${this._x1 = x1},${this._y1 = y1}`;
    } else if (!(l01_2 > epsilon2)) ;
    else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon2) || !r) {
      this._append`L${this._x1 = x1},${this._y1 = y1}`;
    } else {
      let 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), l2 = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2), t01 = l2 / l01, t21 = l2 / l21;
      if (Math.abs(t01 - 1) > epsilon2) {
        this._append`L${x1 + t01 * x01},${y1 + t01 * y01}`;
      }
      this._append`A${r},${r},0,0,${+(y01 * x20 > x01 * y20)},${this._x1 = x1 + t21 * x21},${this._y1 = y1 + t21 * y21}`;
    }
  }
  arc(x2, y2, r, a0, a1, ccw) {
    x2 = +x2, y2 = +y2, r = +r, ccw = !!ccw;
    if (r < 0) throw new Error(`negative radius: ${r}`);
    let dx = r * Math.cos(a0), dy = r * Math.sin(a0), x0 = x2 + dx, y0 = y2 + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0;
    if (this._x1 === null) {
      this._append`M${x0},${y0}`;
    } else if (Math.abs(this._x1 - x0) > epsilon2 || Math.abs(this._y1 - y0) > epsilon2) {
      this._append`L${x0},${y0}`;
    }
    if (!r) return;
    if (da < 0) da = da % tau + tau;
    if (da > tauEpsilon) {
      this._append`A${r},${r},0,1,${cw},${x2 - dx},${y2 - dy}A${r},${r},0,1,${cw},${this._x1 = x0},${this._y1 = y0}`;
    } else if (da > epsilon2) {
      this._append`A${r},${r},0,${+(da >= pi)},${cw},${this._x1 = x2 + r * Math.cos(a1)},${this._y1 = y2 + r * Math.sin(a1)}`;
    }
  }
  rect(x2, y2, w, h) {
    this._append`M${this._x0 = this._x1 = +x2},${this._y0 = this._y1 = +y2}h${w = +w}v${+h}h${-w}Z`;
  }
  toString() {
    return this._;
  }
};
function path() {
  return new Path();
}
path.prototype = Path.prototype;

// node_modules/d3-shape/src/path.js
function withPath(shape) {
  let digits = 3;
  shape.digits = function(_) {
    if (!arguments.length) return digits;
    if (_ == null) {
      digits = null;
    } else {
      const d = Math.floor(_);
      if (!(d >= 0)) throw new RangeError(`invalid digits: ${_}`);
      digits = d;
    }
    return shape;
  };
  return () => new Path(digits);
}

// node_modules/d3-shape/src/array.js
var slice = Array.prototype.slice;
function array_default(x2) {
  return typeof x2 === "object" && "length" in x2 ? x2 : Array.from(x2);
}

// node_modules/d3-shape/src/curve/linear.js
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;
      // falls through
      default:
        this._context.lineTo(x2, y2);
        break;
    }
  }
};
function linear_default(context) {
  return new Linear(context);
}

// node_modules/d3-shape/src/point.js
function x(p) {
  return p[0];
}
function y(p) {
  return p[1];
}

// node_modules/d3-shape/src/line.js
function line_default(x2, y2) {
  var defined = constant_default3(true), context = null, curve = linear_default, output = null, path2 = withPath(line);
  x2 = typeof x2 === "function" ? x2 : x2 === void 0 ? x : constant_default3(x2);
  y2 = typeof y2 === "function" ? y2 : y2 === void 0 ? y : constant_default3(y2);
  function line(data) {
    var i, n2 = (data = array_default(data)).length, d, defined0 = false, buffer;
    if (context == null) output = curve(buffer = path2());
    for (i = 0; i <= n2; ++i) {
      if (!(i < n2 && defined(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) output.lineStart();
        else output.lineEnd();
      }
      if (defined0) output.point(+x2(d, i, data), +y2(d, i, data));
    }
    if (buffer) return output = null, buffer + "" || null;
  }
  line.x = function(_) {
    return arguments.length ? (x2 = typeof _ === "function" ? _ : constant_default3(+_), line) : x2;
  };
  line.y = function(_) {
    return arguments.length ? (y2 = typeof _ === "function" ? _ : constant_default3(+_), line) : y2;
  };
  line.defined = function(_) {
    return arguments.length ? (defined = typeof _ === "function" ? _ : constant_default3(!!_), line) : defined;
  };
  line.curve = function(_) {
    return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;
  };
  line.context = function(_) {
    return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;
  };
  return line;
}

// src/spectraplot.mts
var SPECTRA_ELEMENT = "sp-spectra";
var FreqAmp = class {
  constructor(freq, values) {
    this.freq = freq;
    this.values = values;
    this.inputUnits = "";
    this.seismogramDisplayData = null;
    if (freq.length !== values.length) {
      throw new Error(
        `Frequencies and complex values must have same length: ${freq.length} ${values.length}`
      );
    }
  }
  frequencies() {
    return this.freq;
  }
  amplitudes() {
    const out = new Float32Array(this.values.length);
    this.values.forEach((c, i) => out[i] = c.abs());
    return out;
  }
  phases() {
    const out = new Float32Array(this.values.length);
    this.values.forEach((c, i) => out[i] = c.angle());
    return out;
  }
  get numFrequencies() {
    return this.freq.length;
  }
  get minFrequency() {
    return this.fundamentalFrequency;
  }
  get maxFrequency() {
    return this.freq[this.freq.length - 1];
  }
  // for compatibility with FFTResult
  get fundamentalFrequency() {
    return this.freq[0];
  }
};
var spectra_plot_css = `
:host {
  display: block
}

div.wrapper {
  height: 100%;
  min-height: 100px;
}
path.fftpath {
  stroke: skyblue;
  fill: none;
  stroke-width: 1px;
}

svg.spectra_plot {
  height: 100%;
  width: 100%;
  min-height: 100px;
  display: block;
}
svg.spectra_plot text.title {
  font-size: larger;
  font-weight: bold;
  fill: black;
  color: black;
}

svg.spectra_plot text.sublabel {
  font-size: smaller;
}

/* links in svg */
svg.spectra_plot text a {
  fill: #0000EE;
  text-decoration: underline;
}

`;
var AMPLITUDE = "amplitude";
var PHASE = "phase";
var LOGFREQ = "logfreq";
var KIND = "kind";
var SpectraPlot = class extends HTMLElement {
  constructor(fftResults, seismographConfig) {
    super();
    if (seismographConfig) {
      this._seismographConfig = seismographConfig;
    } else {
      this._seismographConfig = new SeismographConfig();
    }
    if (fftResults) {
      this._fftResults = fftResults;
    } else {
      this._fftResults = [];
    }
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    addStyleToElement(this, spectra_plot_css);
    const lineColorsCSS = this.seismographConfig.createCSSForLineColors();
    addStyleToElement(this, lineColorsCSS, COLOR_CSS_ID);
    this.shadowRoot?.appendChild(wrapper);
  }
  get fftResults() {
    return this._fftResults;
  }
  set fftResults(fftResults) {
    this._fftResults = fftResults;
    this.draw();
  }
  get seismographConfig() {
    return this._seismographConfig;
  }
  set seismographConfig(seismographConfig) {
    this._seismographConfig = seismographConfig;
    this.draw();
  }
  get kind() {
    let k = this.hasAttribute(KIND) ? this.getAttribute(KIND) : AMPLITUDE;
    if (!k) {
      k = AMPLITUDE;
    }
    return k;
  }
  set kind(val) {
    this.setAttribute(KIND, val);
  }
  get logfreq() {
    if (!this.hasAttribute(LOGFREQ)) {
      return true;
    }
    const b = this.getAttribute(LOGFREQ);
    if (b && b.toLowerCase() === "true") {
      return true;
    }
    return false;
  }
  set logfreq(val) {
    this.setAttribute(LOGFREQ, `${val}`);
  }
  connectedCallback() {
    this.draw();
  }
  static get observedAttributes() {
    return [LOGFREQ, KIND];
  }
  attributeChangedCallback(_name, _oldValue, _newValue) {
    this.draw();
  }
  draw() {
    if (!this.isConnected) {
      return;
    }
    const ampPhaseList = [];
    let maxFFTAmpLen = 0;
    const extentFFTData = [];
    const freqMinMax = [];
    if (this.kind === PHASE) {
      extentFFTData.push(-Math.PI);
      extentFFTData.push(Math.PI);
      if (this.seismographConfig.ySublabelIsUnits) {
        this.seismographConfig.ySublabelIsUnits = false;
        this.seismographConfig.ySublabel = "Radian";
      }
    } else {
      if (this.seismographConfig.ySublabelIsUnits) {
        this.seismographConfig.ySublabelIsUnits = false;
        this.seismographConfig.ySublabel = "";
      }
    }
    for (const fftA of this.fftResults) {
      if (this.logfreq === true) {
        freqMinMax.push(fftA.fundamentalFrequency);
      } else {
        freqMinMax.push(0);
      }
      freqMinMax.push(fftA.maxFrequency);
      let ap;
      if (fftA instanceof FFTResult || fftA instanceof FreqAmp) {
        ap = fftA;
      } else {
        throw new Error("fftResults must be array of FFTResult");
      }
      ampPhaseList.push(ap);
      if (maxFFTAmpLen < ap.numFrequencies) {
        maxFFTAmpLen = ap.numFrequencies;
      }
      let ampSlice;
      if (this.kind === AMPLITUDE) {
        ampSlice = ap.amplitudes();
      } else if (this.kind === PHASE) {
        ampSlice = ap.phases();
      } else {
        throw new Error(`Unknown plot kind=${this.kind}`);
      }
      if (this.kind === AMPLITUDE) {
        ampSlice = ampSlice.slice(1);
      }
      const currExtent = extent(ampSlice);
      if (this.kind === AMPLITUDE && currExtent[0] === 0) {
        currExtent[0] = 0.1 * ampSlice.reduce(function(acc, curr) {
          if (curr > 0 && curr < acc) {
            return curr;
          } else {
            return acc;
          }
        }, 1e-9);
      }
      if (currExtent[0]) {
        extentFFTData.push(currExtent[0]);
      }
      if (currExtent[1]) {
        extentFFTData.push(currExtent[1]);
      }
    }
    if (freqMinMax.length < 2) {
      freqMinMax.push(0.1);
      freqMinMax.push(10);
    }
    if (extentFFTData.length < 2) {
      extentFFTData.push(0.1);
      extentFFTData.push(1);
    }
    const wrapper = this.shadowRoot?.querySelector("div");
    while (wrapper.lastChild) {
      wrapper.removeChild(wrapper.lastChild);
    }
    const svg_element = document.createElementNS(SVG_NS, "svg");
    wrapper.appendChild(svg_element);
    const svg = select_default2(svg_element);
    svg.classed("spectra_plot", true).classed(AUTO_COLOR_SELECTOR, true);
    const rect = svg_element.getBoundingClientRect();
    const width = +rect.width - this.seismographConfig.margin.left - this.seismographConfig.margin.right;
    const height = +rect.height - this.seismographConfig.margin.top - this.seismographConfig.margin.bottom;
    const g = svg.append("g").attr(
      "transform",
      "translate(" + this.seismographConfig.margin.left + "," + this.seismographConfig.margin.top + ")"
    );
    let xScale;
    if (this.logfreq) {
      xScale = log2().rangeRound([0, width]);
    } else {
      xScale = linear2().rangeRound([0, width]);
    }
    const freqMin = freqMinMax.reduce((acc, cur) => Math.min(acc, cur));
    const freqMax = freqMinMax.reduce((acc, cur) => Math.max(acc, cur));
    xScale.domain([freqMin, freqMax]);
    let fftMin = extentFFTData.reduce(
      (acc, cur) => Math.min(acc, cur),
      Number.MAX_VALUE
    );
    let fftMax = extentFFTData.reduce((acc, cur) => Math.max(acc, cur), -1);
    if ((fftMax - fftMin) / fftMax < 0.1) {
      fftMin = fftMin * 0.1;
      fftMax = fftMax * 2;
    }
    let yScale;
    if (this.kind === AMPLITUDE) {
      yScale = log2().rangeRound([height, 0]);
      yScale.domain([fftMin, fftMax]);
      if (yScale.domain()[0] === yScale.domain()[1]) {
        yScale.domain([yScale.domain()[0] / 2, yScale.domain()[1] * 2]);
      }
    } else {
      yScale = linear2().rangeRound([height, 0]);
      yScale.domain([fftMin, fftMax]);
      if (yScale.domain()[0] === yScale.domain()[1]) {
        yScale.domain([yScale.domain()[0] - 1, yScale.domain()[1] + 1]);
      }
    }
    const xAxis = axisBottom(xScale);
    g.append("g").attr("transform", "translate(0," + height + ")").call(xAxis);
    const yAxis = axisLeft(yScale);
    g.append("g").call(yAxis);
    this.seismographConfig.yLabel = "Amplitude";
    if (this.kind === PHASE) {
      this.seismographConfig.yLabel = "Phase";
    }
    this.seismographConfig.xLabel = "Frequency";
    this.seismographConfig.xSublabel = "Hz";
    if (this.seismographConfig.ySublabelIsUnits) {
      if (this.kind === PHASE) {
        this.seismographConfig.ySublabel = "radian";
      } else {
        this.seismographConfig.ySublabel = "";
        for (const ap of ampPhaseList) {
          this.seismographConfig.ySublabel += ap.inputUnits;
        }
      }
    }
    const pathg = g.append("g").classed(G_DATA_SELECTOR, true);
    for (const ap of ampPhaseList) {
      let ampSlice;
      if (this.kind === AMPLITUDE) {
        ampSlice = ap.amplitudes();
      } else if (this.kind === PHASE) {
        ampSlice = ap.phases();
      } else {
        throw new Error(`Unknown plot kind=${this.kind}`);
      }
      let freqSlice = ap.frequencies();
      if (this.logfreq) {
        freqSlice = freqSlice.slice(1);
        ampSlice = ampSlice.slice(1);
      }
      const line = line_default();
      line.x(function(d, i) {
        return xScale(freqSlice[i]);
      });
      line.y(function(d) {
        if (d !== 0 && !isNaN(d)) {
          return yScale(d);
        } else {
          return yScale.range()[0];
        }
      });
      pathg.append("g").append("path").classed("fftpath", true).datum(ampSlice).attr("d", line);
    }
    const handlebarInput = {
      seisDataList: this.fftResults.map((f) => f.seismogramDisplayData),
      seisConfig: this.seismographConfig
    };
    drawAxisLabels(
      svg_element,
      this.seismographConfig,
      height,
      width,
      handlebarInput
    );
  }
};
customElements.define(SPECTRA_ELEMENT, SpectraPlot);

// src/particlemotion.mts
var particlemotion_exports = {};
__export(particlemotion_exports, {
  DEFAULT_TITLE: () => DEFAULT_TITLE2,
  DEFAULT_XLABEL: () => DEFAULT_XLABEL,
  DEFAULT_YLABEL: () => DEFAULT_YLABEL,
  PARTICLE_MOTION_ELEMENT: () => PARTICLE_MOTION_ELEMENT,
  ParticleMotion: () => ParticleMotion,
  createParticleMotionConfig: () => createParticleMotionConfig,
  particleMotion_css: () => particleMotion_css
});
var DEFAULT_TITLE2 = "<tspan>{{#each seisDataList}}{{onlyChangesChannel ../seisDataList @index}} {{else}}No Data{{/each}}</tspan>";
var DEFAULT_XLABEL = "{{#each seisXData}}<tspan>{{this.channelCode}}</tspan> {{else}}No Data{{/each}}";
var DEFAULT_YLABEL = "{{#each seisYData}}<tspan>{{this.channelCode}}</tspan> {{else}}No Data{{/each}}";
var PARTICLE_MOTION_ELEMENT = "sp-particle-motion";
var particleMotion_css = `

:host {
  display: block;
  min-height: 200px;
  height: 100%;
}

div.wrapper {
  min-height: 100px;
  height: 100%;
  width: 100%;
}

svg {
  height: 100%;
  width: 100%;
  min-height: 125px;
  min-width: 125px;
  z-index: 100;
}

svg text.title {
  font-size: larger;
  font-weight: bold;
  fill: black;
  color: black;
}

svg path.seispath {
    stroke: skyblue;
    fill: none;
    stroke-width: 1px;
}
`;
function createParticleMotionConfig(timeRange, defaultSeisConfig) {
  let seisConfig;
  if (defaultSeisConfig) {
    seisConfig = defaultSeisConfig.clone();
  } else {
    seisConfig = new SeismographConfig();
  }
  seisConfig.title = DEFAULT_TITLE2;
  if (isDef(timeRange)) {
    seisConfig.fixedTimeScale = timeRange;
  }
  seisConfig.xLabel = DEFAULT_XLABEL;
  seisConfig.yLabel = DEFAULT_YLABEL;
  seisConfig.xSublabelIsUnits = true;
  seisConfig.ySublabelIsUnits = true;
  seisConfig.margin.top = 20;
  seisConfig.margin.bottom = 45;
  seisConfig.margin.right = 40;
  seisConfig.margin.left = 40;
  return seisConfig;
}
var ParticleMotion = class _ParticleMotion extends SeisPlotElement {
  constructor(xSeisData, ySeisData, seisConfig) {
    if (!xSeisData) {
      xSeisData = [];
    }
    if (xSeisData instanceof Seismogram) {
      xSeisData = [SeismogramDisplayData.fromSeismogram(xSeisData)];
    }
    if (!Array.isArray(xSeisData)) {
      xSeisData = [xSeisData];
    }
    if (!ySeisData) {
      ySeisData = [];
    }
    if (!Array.isArray(ySeisData)) {
      ySeisData = [ySeisData];
    }
    const seisData = xSeisData.concat(ySeisData);
    if (!seisConfig) {
      seisConfig = createParticleMotionConfig();
    }
    super(seisData, seisConfig);
    this.outerWidth = -1;
    this.outerHeight = -1;
    this._xSeisData = xSeisData;
    this._ySeisData = ySeisData;
    this.addStyle(particleMotion_css);
    const lineColorsCSS = this.seismographConfig.createCSSForLineColors();
    this.addStyle(lineColorsCSS, COLOR_CSS_ID);
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    const svgWrapped = wrapper.appendChild(
      document.createElementNS(SVG_NS, "svg")
    );
    this.getShadowRoot().appendChild(wrapper);
    const svg = select_default2(svgWrapped);
    this.plotId = ++_ParticleMotion._lastID;
    if (this.xSeisData.length !== this.ySeisData.length) {
      throw new Error(
        `xSeisData and ySeisData should have same length: ${this.xSeisData.length} !== ${this.ySeisData.length}`
      );
    }
    svg.attr("version", "1.1");
    svg.classed("particleMotion", true);
    svg.attr("plotId", this.plotId);
    this.xScale = linear2();
    this.xScaleRmean = linear2();
    this.yScale = linear2();
    this.yScaleRmean = linear2();
    if (this.seismographConfig.isCenteredAmp()) {
      this.xAxis = axisBottom(this.xScaleRmean);
      this.yAxis = axisLeft(this.yScaleRmean);
    } else {
      this.xAxis = axisBottom(this.xScale);
      this.yAxis = axisLeft(this.yScale);
    }
    this.xAxis.ticks(
      this.seismographConfig.yAxisNumTickHint,
      this.seismographConfig.amplitudeFormat
    ).tickFormat(
      numberFormatWrapper(this.seismographConfig.amplitudeFormat)
    );
    this.yAxis.ticks(
      this.seismographConfig.yAxisNumTickHint,
      this.seismographConfig.amplitudeFormat
    ).tickFormat(
      numberFormatWrapper(this.seismographConfig.amplitudeFormat)
    );
    this.width = 100;
    this.height = 100;
    const arrow = svg.append("defs").append("marker");
    arrow.attr("id", "arrow").attr("markerWidth", "10").attr("markerHeight", "10").attr("refX", "0").attr("refY", "3").attr("orient", "auto").attr("markerUnits", "strokeWidth");
    arrow.append("path").attr("d", "M0,0 L0,6 L9,3 z").attr("stroke", "currentColor").attr("fill", "currentColor");
    this.g = svg.append("g").attr(
      "transform",
      "translate(" + this.seismographConfig.margin.left + "," + this.seismographConfig.margin.top + ")"
    );
    this.calcScaleDomain();
    select_default2(window).on("resize.particleMotion" + this.plotId, () => {
      if (this.checkResize()) {
        this.redraw();
      }
    });
  }
  get xSeisData() {
    return this._xSeisData;
  }
  set xSeisData(xsdd) {
    if (Array.isArray(xsdd)) {
      this._xSeisData = xsdd;
    } else if (xsdd instanceof SeismogramDisplayData) {
      this._xSeisData = [xsdd];
    } else {
      throw new Error(`Unknown data for xSeisData`);
    }
    this._seisDataList = this._xSeisData.concat(this._ySeisData);
  }
  get ySeisData() {
    return this._ySeisData;
  }
  set ySeisData(ysdd) {
    if (Array.isArray(ysdd)) {
      this._ySeisData = ysdd;
    } else if (ysdd instanceof SeismogramDisplayData) {
      this._ySeisData = [ysdd];
    } else {
      throw new Error(`Unknown data for xSeisData:`);
    }
    this._seisDataList = this._xSeisData.concat(this._ySeisData);
  }
  draw() {
    if (!this.isConnected) {
      return;
    }
    const wrapper = this.getShadowRoot().querySelector("div");
    const svgEl = wrapper.querySelector("svg");
    if (!svgEl) {
      return;
    }
    const rect = svgEl.getBoundingClientRect();
    let calcHeight = rect.height;
    if (rect.width !== this.outerWidth || rect.height !== this.outerHeight) {
      if (isNumArg(this.seismographConfig.minHeight) && calcHeight < this.seismographConfig.minHeight) {
        calcHeight = this.seismographConfig.minHeight;
      }
      if (isNumArg(this.seismographConfig.maxHeight) && calcHeight > this.seismographConfig.maxHeight) {
        calcHeight = this.seismographConfig.maxHeight;
      }
      this.calcWidthHeight(rect.width, calcHeight);
    }
    this.calcScaleDomain();
    this.drawAxis();
    const handlebarsInput = this.createHandlebarsInput();
    drawAxisLabels(
      svgEl,
      this.seismographConfig,
      this.height,
      this.width,
      handlebarsInput
    );
    this.drawParticleMotion();
  }
  checkResize() {
    const wrapper = this.getShadowRoot().querySelector("div");
    const svgEl = wrapper.querySelector("svg");
    const rect = svgEl.getBoundingClientRect();
    if (rect.width !== this.outerWidth || rect.height !== this.outerHeight) {
      return true;
    }
    return false;
  }
  drawParticleMotion() {
    this.g.selectAll("g.particleMotion").remove();
    if (!this.xSeisData || this.xSeisData.length === 0 || !this.ySeisData || this.ySeisData.length === 0) {
      return;
    }
    const lineG = this.g.append("g");
    let xOrientCode = "X";
    let yOrientCode = "Y";
    if (this.xSeisData[0].channelCode && this.xSeisData[0].channelCode.length > 2) {
      xOrientCode = this.xSeisData[0].channelCode.charAt(2);
    }
    if (this.ySeisData[0].channelCode && this.ySeisData[0].channelCode.length > 2) {
      yOrientCode = this.ySeisData[0].channelCode.charAt(2);
    }
    lineG.classed("particleMotion", true).classed("seisplotjsdata", true).classed("seispath", true).classed(this.xSeisData[0].codes(), true).classed("orient" + xOrientCode + "_" + yOrientCode, true);
    let xSegments;
    let ySegments;
    for (let i = 0; i < this.xSeisData.length; i++) {
      xSegments = this.xSeisData[i].segments;
      ySegments = this.ySeisData[i].segments;
      xSegments.forEach((segX) => {
        ySegments.forEach((segY) => {
          this.drawParticleMotionForSegment(lineG, segX, segY);
        });
      });
    }
  }
  drawParticleMotionForSegment(lineG, segA, segB) {
    const timeRange = segA.timeRange.intersection(segB.timeRange);
    if (!isDef(timeRange)) {
      return;
    }
    const s2 = validStartTime(timeRange);
    const e = validEndTime(timeRange);
    const idxA = segA.indexOfTime(s2);
    const lastIdxA = segA.indexOfTime(e);
    const idxB = segB.indexOfTime(s2);
    const lastIdxB = segB.indexOfTime(e);
    if (idxA === -1 || lastIdxA === -1 || idxB === -1 || lastIdxB === -1) {
      return;
    }
    const numPts = Math.min(lastIdxA - idxA, lastIdxB - idxB) + 1;
    const segmentG = lineG.append("g").classed("segment", true);
    const path2 = segmentG.selectAll("path").data([segA.y.slice(idxA, numPts)]);
    path2.exit().remove();
    path2.enter().append("path").classed("seispath", true).attr("marker-end", "url(#arrow)").attr(
      "d",
      // @ts-expect-error no idea why typescript thinks dd is [number, number] when it is just number
      line_default().curve(linear_default).x((dd) => {
        return this.xScale(dd);
      }).y((d, i) => {
        return this.yScale(segB.yAtIndex(idxB + i));
      })
    );
  }
  drawAxis() {
    const svgG = this.g;
    svgG.selectAll("g.axis").remove();
    svgG.append("g").attr("class", "axis axis--x").attr("transform", "translate(0," + this.height + ")").call(this.xAxis);
    svgG.append("g").attr("class", "axis axis--y").call(this.yAxis);
  }
  rescaleAxis() {
    const delay = 500;
    const yaxisG = this.g.select(".axis--y");
    yaxisG.transition().duration(delay / 2).call(this.yAxis);
    const xaxisG = this.g.select(".axis--x");
    xaxisG.transition().duration(delay / 2).call(this.xAxis);
  }
  calcScaleDomain() {
    if (this.seismographConfig.fixedAmplitudeScale) {
      this.xScale.domain(this.seismographConfig.fixedAmplitudeScale).nice();
      this.yScale.domain(this.seismographConfig.fixedAmplitudeScale).nice();
    } else {
      let xMinMax = new MinMaxable(-1, 1);
      if (this.xSeisData) {
        xMinMax = findMinMaxOfSDD(this.xSeisData);
      }
      let yMinMax = new MinMaxable(-1, 1);
      if (this.ySeisData) {
        yMinMax = findMinMaxOfSDD(this.ySeisData);
      }
      let halfDomainDelta = xMinMax.halfWidth;
      if (yMinMax.halfWidth > halfDomainDelta) {
        halfDomainDelta = yMinMax.halfWidth;
      }
      const xMid = xMinMax.middle;
      const yMid = yMinMax.middle;
      const xMinMaxArr = [xMid - halfDomainDelta, xMid + halfDomainDelta];
      const yMinMaxArr = [yMid - halfDomainDelta, yMid + halfDomainDelta];
      this.xScale.domain(xMinMaxArr).nice();
      this.yScale.domain(yMinMaxArr).nice();
    }
    const xNiceMinMax = this.xScale.domain();
    const xHalfNice = (xNiceMinMax[1] - xNiceMinMax[0]) / 2;
    if (this.seismographConfig.isCenteredAmp()) {
      this.xScaleRmean.domain([-1 * xHalfNice, xHalfNice]);
    } else {
      this.xScaleRmean.domain(this.xScale.domain());
    }
    const yNiceMinMax = this.yScale.domain();
    const yHalfNice = (yNiceMinMax[1] - yNiceMinMax[0]) / 2;
    if (this.seismographConfig.isCenteredAmp()) {
      this.yScaleRmean.domain([-1 * yHalfNice, yHalfNice]);
    } else {
      this.yScaleRmean.domain(this.yScale.domain());
    }
    this.rescaleAxis();
  }
  calcWidthHeight(nOuterWidth, nOuterHeight) {
    const defHW = 200;
    this.outerWidth = nOuterWidth ? Math.max(defHW, nOuterWidth) : defHW;
    this.outerHeight = nOuterHeight ? Math.max(defHW, nOuterHeight) : defHW;
    this.height = this.outerHeight - this.seismographConfig.margin.top - this.seismographConfig.margin.bottom;
    this.width = this.outerWidth - this.seismographConfig.margin.left - this.seismographConfig.margin.right;
    this.height = Math.min(this.height, this.width);
    this.width = Math.min(this.height, this.width);
    this.xScale.range([0, this.width]);
    this.yScale.range([this.height, 0]);
    this.xScaleRmean.range([0, this.width]);
    this.yScaleRmean.range([this.height, 0]);
  }
  createHandlebarsInput() {
    return {
      seisDataList: this._seisDataList,
      seisConfig: this._seismographConfig,
      seisXData: this.xSeisData,
      seisYData: this.ySeisData
    };
  }
};
ParticleMotion._lastID = 0;
customElements.define(PARTICLE_MOTION_ELEMENT, ParticleMotion);

// src/organizeddisplayitem.mts
var querystringify = __toESM(require_querystringify(), 1);
var ORG_DISP_ITEM = "sp-organized-display-item";
var PLOT_TYPE = "plottype";
var SEISMOGRAPH = "seismograph";
var SPECTRA = "amp_spectra";
var PARTICLE_MOTION = "particlemotion";
var MAP = "map";
var INFO2 = "info";
var OrganizedDisplayItem = class extends SeisPlotElement {
  constructor(seisData, seisConfig) {
    super(seisData, seisConfig);
    if (this.plottype.startsWith(PARTICLE_MOTION)) {
      this._seismographConfig = createParticleMotionConfig(null, seisConfig);
    }
    this.extras = /* @__PURE__ */ new Map();
    this.addStyle(`
    :host {
      display: block;
      min-height: 50px;

    }
    sp-station-quake-map {
      height: 400px;
    }
    sp-seismograph {
      height: var(--sp-seismograph-height, 200px);
    }
    div.wrapper {
      height: 100%;
    }
    `);
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    this.getShadowRoot().appendChild(wrapper);
  }
  get plottype() {
    let k = this.hasAttribute(PLOT_TYPE) ? this.getAttribute(PLOT_TYPE) : SEISMOGRAPH;
    if (!k) {
      k = SEISMOGRAPH;
    }
    return k;
  }
  set plottype(val) {
    this.setAttribute(PLOT_TYPE, val);
    this.redraw();
  }
  set seismographConfig(seismographConfig) {
    super.seismographConfig = seismographConfig;
    this.getContainedPlotElements().forEach((spe) => {
      spe.seismographConfig = seismographConfig;
    });
    this.seisDataUpdated();
  }
  static get observedAttributes() {
    return [PLOT_TYPE];
  }
  attributeChangedCallback(_name, _oldValue, _newValue) {
    this.redraw();
  }
  setExtra(key, value) {
    this.extras.set(key, value);
  }
  hasExtra(key) {
    return this.extras.has(key);
  }
  getExtra(key) {
    if (this.extras.has(key)) {
      return this.extras.get(key);
    }
    return null;
  }
  getContainedPlotElements() {
    const wrapper = this.getShadowRoot().querySelector("div");
    let dispItems = Array.from(wrapper.children);
    dispItems = dispItems.filter((el) => el instanceof SeisPlotElement);
    return dispItems;
  }
  draw() {
    if (!this.isConnected) {
      return;
    }
    const wrapper = this.getShadowRoot().querySelector("div");
    while (wrapper.firstChild) {
      wrapper.removeChild(wrapper.lastChild);
    }
    const qIndex = this.plottype.indexOf("?");
    let queryParams;
    if (qIndex !== -1) {
      queryParams = querystringify.parse(
        this.plottype.substring(qIndex)
      );
    } else {
      queryParams = {};
    }
    if (this.plottype.startsWith(SEISMOGRAPH)) {
      const seismograph = new Seismograph(
        this.seisData,
        this._seismographConfig
      );
      wrapper.appendChild(seismograph);
    } else if (this.plottype.startsWith(SPECTRA)) {
      const loglog = getFromQueryParams(queryParams, "loglog", "true");
      const nonContigList = this.seisData.filter(
        (sdd) => !(sdd.seismogram && sdd.seismogram.isContiguous())
      );
      if (nonContigList.length > 0) {
        const nonContigMsg = "non-contiguous seismograms, skipping: " + nonContigList.map(
          (sdd) => isDef(sdd.seismogram) ? `${sdd.codes()} ${sdd.seismogram.segments.length}` : "null"
        ).join(",");
        const p = wrapper.appendChild(document.createElement("p"));
        p.textContent = nonContigMsg;
      }
      const fftList = this.seisData.map((sdd) => {
        return sdd.seismogram && sdd.seismogram.isContiguous() ? fftForward(sdd) : null;
      });
      const fftListNoNull = fftList.filter(isDef);
      const spectraPlot = new SpectraPlot(
        fftListNoNull,
        this._seismographConfig
      );
      spectraPlot.setAttribute(LOGFREQ, loglog);
      wrapper.appendChild(spectraPlot);
    } else if (this.plottype.startsWith(PARTICLE_MOTION)) {
      if (this.seisData.length !== 2) {
        throw new Error(
          `particle motion requies exactly 2 seisData in seisDataList, ${this.seisData.length}`
        );
      }
      const pmpSeisConfig = this._seismographConfig.clone();
      const particleMotionPlot = new ParticleMotion(
        [this.seisData[0]],
        [this.seisData[1]],
        pmpSeisConfig
      );
      wrapper.appendChild(particleMotionPlot);
    } else if (this.plottype.startsWith(MAP)) {
      const mapid = "map" + ((1 + Math.random()) * 65536 | 0).toString(16).substring(1);
      const seismap = new QuakeStationMap(this.seisData);
      seismap.setAttribute("id", mapid);
      for (const mapAttr of QuakeStationMap.observedAttributes) {
        if (queryParams[mapAttr]) {
          seismap.setAttribute(mapAttr, getFromQueryParams(queryParams, mapAttr));
        }
      }
      wrapper.appendChild(seismap);
    } else if (this.plottype.startsWith(INFO2)) {
      const infotable = new QuakeStationTable(
        this.seisData,
        this._seismographConfig
      );
      wrapper.appendChild(infotable);
    } else {
      throw new Error(`Unkown plottype "${this.plottype}"`);
    }
  }
};
customElements.define(ORG_DISP_ITEM, OrganizedDisplayItem);
function getFromQueryParams(qParams, name, defaultValue = "") {
  if (name in qParams) {
    const v = qParams[name];
    if (isStringArg(v)) {
      return v;
    } else {
      throw new Error(
        `param ${name} exists but is not string: ${stringify(qParams[name])}`
      );
    }
  }
  return defaultValue;
}

// src/organizeddisplay.mts
var ORG_DISPLAY = "sp-organized-display";
var ORG_TYPE = "orgtype";
var WITH_INFO = "info";
var DEFAULT_WITH_INFO = "false";
var WITH_MAP = "map";
var DEFAULT_WITH_MAP = "false";
var WITH_TOOLS = "tools";
var DEFAULT_WITH_TOOLS = "true";
var OVERLAY_BY = "overlay";
var OVERLAY_NONE = "none";
var OVERLAY_INDIVIDUAL = "individual";
var OVERLAY_VECTOR = "vector";
var OVERLAY_COMPONENT = "component";
var OVERLAY_STATION = "station";
var OVERLAY_STATION_COMPONENT = "stationcomponent";
var OVERLAY_ALL = "all";
var OVERLAY_FUNCTION = "function";
var OrganizedDisplay = class extends SeisPlotElement {
  constructor(seisData, seisConfig) {
    super(seisData, seisConfig);
    this.bottomSeismographConfig = null;
    this.topSeismographConfig = null;
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    this.addStyle(`
    :host {
      display: block;
      min-height: 50px;
      height: 100%;
    }
    @property --sp-seismograph-height {
      syntax: "<length>";
      inherits: true;
      initial-value: 200px;
    }
    sp-station-quake-map {
      height: var(--map-height, 400px);
    }
    sp-organized-display-item {
      min-height: var(--sp-seismograph-height, 200px);
    }
    div.wrapper {
      height: 100%;
    }
    `);
    this.getShadowRoot().appendChild(wrapper);
  }
  static get observedAttributes() {
    const sup = super.observedAttributes;
    const mine = sup.concat([
      ORG_TYPE,
      WITH_TOOLS,
      WITH_MAP,
      WITH_INFO,
      OVERLAY_BY
    ]);
    const map4 = QuakeStationMap.observedAttributes;
    return mine.concat(map4);
  }
  getDisplayItems() {
    const wrapper = this.getShadowRoot().querySelector("div");
    let dispItems = Array.from(wrapper.children);
    dispItems = dispItems.filter((el) => el instanceof OrganizedDisplayItem);
    return dispItems;
  }
  get orgtype() {
    let k = this.hasAttribute(ORG_TYPE) ? this.getAttribute(ORG_TYPE) : OVERLAY_INDIVIDUAL;
    if (!k) {
      k = SEISMOGRAPH;
    }
    return k;
  }
  set orgtype(val) {
    this.setAttribute(ORG_TYPE, val);
    this.redraw();
  }
  get tools() {
    let k = this.hasAttribute(WITH_TOOLS) ? this.getAttribute(WITH_TOOLS) : DEFAULT_WITH_TOOLS;
    if (!isDef(k)) {
      k = DEFAULT_WITH_TOOLS;
    }
    k = k.trim().toLowerCase();
    return k;
  }
  set tools(val) {
    this.setAttribute(WITH_TOOLS, val);
  }
  get map() {
    let k = this.hasAttribute(WITH_MAP) ? this.getAttribute(WITH_MAP) : DEFAULT_WITH_MAP;
    if (!isDef(k)) {
      k = DEFAULT_WITH_MAP;
    }
    k = k.trim().toLowerCase();
    return k;
  }
  set map(val) {
    this.setAttribute(WITH_MAP, val);
  }
  get info() {
    let k = this.hasAttribute(WITH_INFO) ? this.getAttribute(WITH_INFO) : DEFAULT_WITH_INFO;
    if (!isDef(k)) {
      k = DEFAULT_WITH_INFO;
    }
    k = k.trim().toLowerCase();
    return k;
  }
  set info(val) {
    this.setAttribute(WITH_INFO, val.toLowerCase().trim());
  }
  get overlayby() {
    let k = this.hasAttribute(OVERLAY_BY) ? this.getAttribute(OVERLAY_BY) : OVERLAY_INDIVIDUAL;
    if (!k) {
      k = OVERLAY_INDIVIDUAL;
    }
    return k;
  }
  set overlayby(val) {
    this.setAttribute(OVERLAY_BY, val);
  }
  selectedData() {
    const sortedData = this.sortedSeisData();
    const wrapper = this.getShadowRoot().querySelector("div");
    const toolsElement = wrapper.querySelector(ORG_DISP_TOOLS_ELEMENT)?.shadowRoot?.querySelector("div");
    const selectedData = sortedData.filter((sdd) => defaultPlotSelect(sdd, toolsElement));
    return selectedData;
  }
  draw() {
    if (!this.isConnected) {
      return;
    }
    const allData = this.sortedSeisData();
    const selectedData = this.selectedData();
    this.drawTools(allData);
    this.drawMap(allData, selectedData);
    this.drawInfo(selectedData);
    this.drawSeismograph(selectedData);
  }
  drawSeismograph(sortedData) {
    let seisDispItems = new Array();
    if (this.overlayby === OVERLAY_INDIVIDUAL) {
      sortedData.forEach((sdd) => {
        const oi = new OrganizedDisplayItem([sdd], this.seismographConfig);
        oi.plottype = SEISMOGRAPH;
        seisDispItems.push(oi);
      });
    } else if (this.overlayby === OVERLAY_VECTOR) {
      const groupedSDD = groupComponentOfMotion(sortedData);
      groupedSDD.forEach((gsdd) => {
        const oi = new OrganizedDisplayItem(gsdd, this.seismographConfig);
        seisDispItems.push(oi);
      });
    } else if (this.overlayby === OVERLAY_COMPONENT) {
      const oitems = overlayByComponent(sortedData, this.seismographConfig);
      seisDispItems = seisDispItems.concat(oitems);
    } else if (this.overlayby === OVERLAY_STATION_COMPONENT) {
      const oitems = overlayByStationComponent(sortedData, this.seismographConfig);
      seisDispItems = seisDispItems.concat(oitems);
    } else if (this.overlayby === OVERLAY_STATION) {
      const oitems = overlayByStation(sortedData, this.seismographConfig);
      seisDispItems = seisDispItems.concat(oitems);
    } else if (this.overlayby === OVERLAY_ALL) {
      const oi = new OrganizedDisplayItem(sortedData, this.seismographConfig);
      seisDispItems.push(oi);
    } else if (this.overlayby === OVERLAY_NONE) {
    } else {
      throw new Error(`Unknown overlay: ${this.overlayby}`);
    }
    if (this.topSeismographConfig != null && seisDispItems.length > 0) {
      seisDispItems[0].seismographConfig = this.topSeismographConfig;
      if (this.topSeismographConfig.margin.top > this.seismographConfig.margin.top) {
        const sp_height = getComputedStyle(seisDispItems[0]).getPropertyValue("--sp-seismograph-height");
        if (sp_height !== "") {
          seisDispItems[0].addStyle(`sp-seismograph {
            height: ${sp_height};
          }`);
        }
      }
    }
    if (this.bottomSeismographConfig != null && seisDispItems.length > 1) {
      seisDispItems[seisDispItems.length - 1].seismographConfig = this.bottomSeismographConfig;
    }
    const wrapper = this.getShadowRoot().querySelector("div");
    wrapper.querySelectorAll(ORG_DISP_ITEM).forEach((item) => wrapper.removeChild(item));
    seisDispItems.forEach((odi) => {
      if (odi.plottype === SEISMOGRAPH) {
        odi.addEventListener("mouseenter", (_evt) => {
          const mapElement = wrapper.querySelector(MAP_ELEMENT);
          if (mapElement) {
            mapElement.stationHighlight(uniqueStations2(odi.seisData));
            mapElement.quakeHighlight(uniqueQuakes(odi.seisData));
          }
        });
        odi.addEventListener("mouseleave", (_evt) => {
          const mapElement = wrapper.querySelector(MAP_ELEMENT);
          if (mapElement) {
            mapElement.stationUnhighlight();
            mapElement.quakeUnhighlight();
          }
        });
      }
      wrapper.appendChild(odi);
    });
    return seisDispItems;
  }
  getTools() {
    const wrapper = this.getShadowRoot().querySelector("div");
    const toolsElement = wrapper.querySelector(ORG_DISP_TOOLS_ELEMENT);
    if (toolsElement) {
      return toolsElement;
    }
    return null;
  }
  drawTools(sortedData) {
    if (!this.isConnected) {
      return;
    }
    const wrapper = this.getShadowRoot().querySelector("div");
    const toolsElement = wrapper.querySelector(ORG_DISP_TOOLS_ELEMENT);
    if (this.tools !== "true" && toolsElement) {
      wrapper.removeChild(toolsElement);
    } else if (this.tools === "true") {
      if (!isDef(toolsElement)) {
        if (sortedData == null) {
          sortedData = this.sortedSeisData();
        }
        const toolsdisp = new OrganizedDisplayTools(
          sortedData,
          this.seismographConfig
        );
        toolsdisp.organizedDisplay = this;
        wrapper.insertBefore(toolsdisp, wrapper.firstElementChild);
      } else {
        const orgDispTools = toolsElement;
        orgDispTools.updateCheckboxes(this);
      }
    }
  }
  drawMap(allData, sortedData) {
    if (!this.isConnected) {
      return;
    }
    const wrapper = this.getShadowRoot().querySelector("div");
    const mapElement = wrapper.querySelector(MAP_ELEMENT);
    if (this.map !== "true" && mapElement) {
      wrapper.removeChild(mapElement);
    } else if (this.map === "true" && !isDef(mapElement)) {
      const mapdisp = new QuakeStationMap(sortedData, this.seismographConfig);
      QuakeStationMap.observedAttributes.forEach((a) => {
        const my_attr = this.getAttribute(a);
        if (my_attr) {
          mapdisp.setAttribute(a, my_attr);
        }
      });
      const toolsElement = wrapper.querySelector(ORG_DISP_TOOLS_ELEMENT);
      if (toolsElement) {
        if (toolsElement.nextElementSibling) {
          wrapper.insertBefore(mapdisp, toolsElement.nextElementSibling);
        } else {
          wrapper.appendChild(mapdisp);
        }
      } else {
        wrapper.insertBefore(mapdisp, wrapper.firstElementChild);
      }
    }
    if (this.map === "true" && isDef(mapElement)) {
      mapElement.seisData = sortedData;
      const allStations2 = uniqueStations2(allData);
      const selectedStations = uniqueStations2(sortedData);
      const unselectedStations = allStations2.filter((sta) => !selectedStations.includes(sta));
      mapElement.addStation(unselectedStations, UNSELECTED);
    }
  }
  drawInfo(sortedData) {
    if (!this.isConnected) {
      return;
    }
    const wrapper = this.getShadowRoot().querySelector("div");
    const infoElement = wrapper.querySelector(
      INFO_ELEMENT
    );
    if (this.info !== "true" && infoElement) {
      wrapper.removeChild(infoElement);
    } else if (this.info === "true" && !isDef(infoElement)) {
      const sortedData2 = this.selectedData();
      const infoDisp = new QuakeStationTable(
        sortedData2,
        this.seismographConfig
      );
      const toolsElement = wrapper.querySelector(ORG_DISP_TOOLS_ELEMENT);
      const mapElement = wrapper.querySelector(MAP_ELEMENT);
      if (mapElement) {
        if (mapElement.nextElementSibling) {
          wrapper.insertBefore(infoDisp, mapElement.nextElementSibling);
        } else {
          wrapper.appendChild(infoDisp);
        }
      } else if (toolsElement) {
        if (toolsElement.nextElementSibling) {
          wrapper.insertBefore(infoDisp, toolsElement.nextElementSibling);
        } else {
          wrapper.appendChild(infoDisp);
        }
      } else {
        wrapper.insertBefore(infoDisp, wrapper.firstElementChild);
      }
    } else if (this.info === "true" && isDef(infoElement)) {
      infoElement.seisData = sortedData;
    }
  }
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === WITH_MAP) {
      this.drawMap(this.sortedSeisData(), this.selectedData());
    } else if (name === WITH_INFO) {
      const sortedData = this.selectedData();
      this.drawInfo(sortedData);
    } else if (QuakeStationMap.observedAttributes.includes(name)) {
      const wrapper = this.getShadowRoot().querySelector(
        "div"
      );
      const mapElement = wrapper?.querySelector(MAP_ELEMENT);
      if (mapElement) {
        mapElement.setAttribute(name, newValue);
      }
    } else {
      this.redraw();
    }
  }
};
customElements.define(ORG_DISPLAY, OrganizedDisplay);
function individualDisplay(sddList, seisConfig) {
  if (!seisConfig) {
    seisConfig = new SeismographConfig();
  }
  return sddList.map((sdd) => {
    const odisp = new OrganizedDisplayItem([sdd], seisConfig);
    return odisp;
  });
}
function mapAndIndividualDisplay(sddList, seisConfig) {
  if (!seisConfig) {
    seisConfig = new SeismographConfig();
  }
  const map4 = new OrganizedDisplayItem(sddList, seisConfig);
  map4.plottype = MAP;
  const individual = individualDisplay(sddList);
  individual.unshift(map4);
  return individual;
}
function overlayBySDDFunction(sddList, key, sddFun, seisConfig) {
  if (!seisConfig) {
    seisConfig = new SeismographConfig();
  }
  const out = [];
  sddList.forEach((sdd) => {
    let found = false;
    const val = sddFun(sdd);
    if (!isDef(val)) {
      return;
    }
    out.forEach((org) => {
      if (org.getExtra(key) === val) {
        org.seisData.push(sdd);
        found = true;
      }
    });
    if (!found) {
      const org = new OrganizedDisplayItem([sdd], seisConfig);
      org.setExtra(key, val);
      out.push(org);
    }
  });
  return out;
}
function overlayByComponent(sddList, seisConfig) {
  return overlayBySDDFunction(
    sddList,
    "component",
    (sdd) => sdd.sourceId.subsourceCode,
    seisConfig
  );
}
function overlayByStationComponent(sddList, seisConfig) {
  return overlayBySDDFunction(
    sddList,
    "stationcomponent",
    (sdd) => `${sdd.sourceId.stationSourceId().toStringNoPrefix()} ${sdd.sourceId.subsourceCode}`,
    seisConfig
  );
}
function overlayByStation(sddList, seisConfig) {
  return overlayBySDDFunction(
    sddList,
    "station",
    (sdd) => sdd.sourceId.stationSourceId().toStringNoPrefix(),
    seisConfig
  );
}
function overlayAll(sddList, seisConfig) {
  return overlayBySDDFunction(sddList, "all", () => "all", seisConfig);
}
function groupComponentOfMotion(sddList) {
  let tmpSeisDataList = Array.from(sddList);
  const bifurcate = (arr, filter2) => arr.reduce(
    (acc, val) => (acc[filter2(val) ? 0 : 1].push(val), acc),
    [[], []]
  );
  const byFriends = [];
  let first = tmpSeisDataList.shift();
  while (isDef(first)) {
    const isFriend = (sdddB) => isDef(first) && first.networkCode === sdddB.networkCode && first.stationCode === sdddB.stationCode && first.locationCode === sdddB.locationCode && first.channelCode.slice(0, 2) === sdddB.channelCode.slice(0, 2) && first.timeRange.overlaps(sdddB.timeRange);
    const splitArray = bifurcate(tmpSeisDataList, isFriend);
    const nextGroup = splitArray[0];
    nextGroup.unshift(first);
    byFriends.push(nextGroup);
    tmpSeisDataList = splitArray[1];
    first = tmpSeisDataList.shift();
  }
  return byFriends;
}
function createAttribute(organized, key, valueFun) {
  organized.forEach((org) => {
    if (org.seisData.length > 0) {
      const v = valueFun(org);
      org.setExtra(key, v);
    } else {
      org.setExtra(key, null);
    }
  });
  return organized;
}
function createPlots(organized, divElement) {
  organized.forEach((org) => {
    divElement.appendChild(org);
  });
}

// src/animatedseismograph.mts
var AnimatedTimeScaler = class {
  constructor(timeScale, alignmentTime, minRedrawMillis) {
    this.goAnimation = true;
    this.previousStep = Number.NEGATIVE_INFINITY;
    this._animationId = 0;
    this.timeScale = timeScale;
    this.alignmentTime = alignmentTime ? alignmentTime : DateTime.utc();
    if (minRedrawMillis) {
      this.minRedrawMillis = minRedrawMillis;
    }
  }
  animate() {
    this.goAnimation = true;
    window.requestAnimationFrame((timestamp) => this.stepper(timestamp));
  }
  animateOnce() {
    this.goAnimation = false;
    window.requestAnimationFrame((timestamp) => {
      this.previousStep = timestamp;
      this.step();
    });
  }
  pause() {
    this.goAnimation = false;
  }
  stepper(timestamp) {
    this._animationId = 0;
    const elapsed = timestamp - this.previousStep;
    const redrawMillis = this._calcRedrawMillis ? this._calcRedrawMillis : 100;
    if (elapsed > redrawMillis) {
      this.previousStep = timestamp;
      this.step();
    }
    if (this.goAnimation) {
      const now3 = window.performance.now();
      window.setTimeout(
        () => {
          if (this._animationId !== 0) {
            window.cancelAnimationFrame(this._animationId);
          }
          this._animationId = window.requestAnimationFrame(
            (timestamp2) => this.stepper(timestamp2)
          );
        },
        redrawMillis - (now3 - timestamp)
      );
    }
  }
  step() {
    const now3 = DateTime.utc();
    const calcOffset = now3.diff(this.alignmentTime);
    this.timeScale.offset = calcOffset;
  }
};
var RTDisplayContainer = class {
  constructor(rawSeisData, organizedDisplay, animationScaler, packetHandler, config2) {
    this.rawSeisData = rawSeisData;
    this.organizedDisplay = organizedDisplay;
    this.animationScaler = animationScaler;
    this.packetHandler = packetHandler;
    this.config = config2;
    this.resizeObserver = new ResizeObserver((_entries) => {
      if (!config2.minRedrawMillis) {
        this.recalculateRedrawTime().catch((err) => warn(`Error recalculateRedrawTime ${err}`));
      }
    });
    this.resizeObserver.observe(this.organizedDisplay);
  }
  recalculateRedrawTime() {
    const that = this;
    const p = new Promise((resolve) => {
      setTimeout(() => {
        let calcRedraw = calcOnePixelDuration(this.organizedDisplay).toMillis();
        while (this.config.minRedrawMillis && this.config.minRedrawMillis > calcRedraw) {
          calcRedraw = 2 * calcRedraw;
        }
        that.animationScaler._calcRedrawMillis = calcRedraw;
        resolve(that);
      }, 1e3);
    });
    return p;
  }
  removeAllSeisData() {
    while (this.rawSeisData.length > 0) {
      this.rawSeisData.pop();
    }
    this.organizedDisplay.removeAllSeisData();
  }
};
function isValidRTConfig(configObj) {
  if (!configObj || typeof configObj !== "object") {
    throw new TypeError("config is not object");
  }
  const config2 = configObj;
  if (typeof config2.duration === "undefined") {
    config2.duration = Duration.fromISO("PT5M");
  }
  if (typeof config2.alignmentTime === "undefined") {
    config2.alignmentTime = DateTime.utc();
  }
  if (typeof config2.offset === "undefined") {
    config2.offset = Duration.fromMillis(0);
  }
  if (typeof config2.minRedrawMillis === "undefined") {
    config2.minRedrawMillis = null;
  }
  if (typeof config2.networkList === "undefined") {
    config2.networkList = [];
  }
  if (typeof config2.removeTrend === "undefined") {
    config2.removeTrend = false;
  }
  return true;
}
function createRealtimeDisplay(config2) {
  if (!config2) {
    config2 = {};
  }
  if (isValidRTConfig(config2)) {
    return internalCreateRealtimeDisplay(config2);
  } else {
    throw new Error("config is not valid");
  }
}
function internalCreateRealtimeDisplay(config2) {
  const negDuration = config2.duration.negate();
  const timeScale = new AlignmentLinkedTimeScale(
    [],
    negDuration,
    config2.offset
  );
  if (!config2.seismographConfig) {
    config2.seismographConfig = new SeismographConfig();
  }
  config2.seismographConfig.wheelZoom = false;
  config2.seismographConfig.isYAxisNice = false;
  config2.seismographConfig.linkedTimeScale = timeScale;
  config2.seismographConfig.linkedAmplitudeScale = new LinkedAmplitudeScale();
  const animationScaler = new AnimatedTimeScaler(
    timeScale,
    config2.alignmentTime,
    config2.minRedrawMillis
  );
  const rawSeisData = new Array();
  const orgDisp = new OrganizedDisplay([], config2.seismographConfig);
  orgDisp.sortby = SORT_ALPHABETICAL;
  const packetHandler = (packet) => {
    if (!packet) {
      return;
    }
    let msr = null;
    let ms3 = null;
    if (packet instanceof DataLinkPacket) {
      if (packet.isMiniseed()) {
        msr = packet.asMiniseed();
      } else if (packet.isMiniseed3()) {
        ms3 = packet.asMiniseed3();
      }
    } else if (packet instanceof SEPacket) {
      if (packet.isMiniseed()) {
        msr = packet.asMiniseed();
      } else if (packet.isMiniseed3()) {
        ms3 = packet.asMiniseed3();
      }
    } else {
      msr = packet.miniseed;
    }
    let seisSegment;
    if (msr) {
      seisSegment = createSeismogramSegment(msr);
    } else if (ms3) {
      seisSegment = createSeismogramSegment2([ms3]);
    } else {
      return;
    }
    const codes = seisSegment.codes();
    const matchSDD = rawSeisData.find(
      (sdd) => sdd.codes() === codes
    );
    if (matchSDD) {
      matchSDD.append(seisSegment);
      if (matchSDD.timeRange.toDuration().toMillis() > config2.duration.toMillis() * 1.5) {
        const trimInterval = Interval.fromDateTimes(
          DateTime.utc().minus(config2.duration),
          DateTime.utc()
        );
        matchSDD.trimInPlace(trimInterval);
      }
      const dispMatchSDD = orgDisp.seisData.find(
        (sdd) => sdd.codes() === codes
      );
      if (dispMatchSDD) {
        if (config2.removeTrend && matchSDD.seismogram) {
          const dtSeis = removeTrend(matchSDD.seismogram);
          if (dtSeis) {
            dispMatchSDD.seismogram = dtSeis;
          }
        } else {
          dispMatchSDD.seismogram = matchSDD.seismogram;
        }
      } else {
        if (config2.removeTrend && matchSDD.seismogram) {
          const addDispSDD = matchSDD.cloneWithNewSeismogram(removeTrend(matchSDD.seismogram));
          orgDisp.appendSeisData(addDispSDD);
        } else {
          orgDisp.appendSeisData(matchSDD);
        }
      }
    } else {
      const sdd = SeismogramDisplayData.fromSeismogramSegment(seisSegment);
      rawSeisData.push(sdd);
      if (config2.networkList) {
        sdd.associateChannel(config2.networkList);
      }
      sdd.alignmentTime = animationScaler.alignmentTime;
      if (config2.removeTrend && sdd.seismogram) {
        const dispSDD = sdd.cloneWithNewSeismogram(removeTrend(sdd.seismogram));
        orgDisp.appendSeisData(dispSDD);
      } else {
        orgDisp.appendSeisData(sdd);
      }
      orgDisp.seisDataUpdated();
    }
  };
  return new RTDisplayContainer(
    rawSeisData,
    orgDisp,
    animationScaler,
    packetHandler,
    config2
  );
}
function trim(orgDisplay, timeRange) {
  orgDisplay.seisData.forEach((sdd) => {
    sdd.trimInPlace(timeRange);
    sdd.timeRange = timeRange;
  });
}
function calcOnePixelDuration(seismograph) {
  const rect = seismograph.getBoundingClientRect();
  const margin = seismograph.seismographConfig.margin;
  const lts = seismograph.seismographConfig.linkedTimeScale;
  const fts = seismograph.seismographConfig.fixedTimeScale;
  let timerInterval;
  if (lts) {
    timerInterval = lts.duration.toMillis();
  } else if (fts) {
    timerInterval = fts.toDuration().toMillis();
  } else {
    timerInterval = 1e3;
  }
  if (timerInterval < 0) {
    timerInterval *= -1;
  }
  let pixels = rect.width - margin.left - margin.right;
  if (pixels <= 0) {
    pixels = 1e3;
  }
  timerInterval = timerInterval / pixels;
  if (timerInterval === 0) {
    timerInterval = 100;
  }
  while (timerInterval > 0 && timerInterval < 50) {
    timerInterval *= 2;
  }
  if (timerInterval > 250) {
    timerInterval /= 2;
  }
  return Duration.fromMillis(timerInterval);
}

// src/components.mts
var components_exports = {};
__export(components_exports, {
  CHANNEL_CODE_ELEMENT: () => CHANNEL_CODE_ELEMENT,
  CHANNEL_LIST_ELEMENT: () => CHANNEL_LIST_ELEMENT,
  ChannelCodeInput: () => ChannelCodeInput,
  ChannelListChooser: () => ChannelListChooser,
  LATLONBOX_ELEMENT: () => LATLONBOX_ELEMENT,
  LATLONRADIUS_ELEMENT: () => LATLONRADIUS_ELEMENT,
  LATLON_CHOICE_ELEMENT: () => LATLON_CHOICE_ELEMENT,
  LabeledMinMax: () => LabeledMinMax,
  LatLonBoxEl: () => LatLonBoxEl,
  LatLonChoice: () => LatLonChoice,
  LatLonRadiusEl: () => LatLonRadiusEl,
  MINMAX_ELEMENT: () => MINMAX_ELEMENT,
  SOURCEID_LIST_ELEMENT: () => SOURCEID_LIST_ELEMENT,
  SourceIdListChooser: () => SourceIdListChooser,
  labeledNumberInput: () => labeledNumberInput,
  labeledTextInput: () => labeledTextInput,
  numberFromInput: () => numberFromInput,
  numberOrNaN: () => numberOrNaN,
  validateLatitude: () => validateLatitude,
  validateLongitude: () => validateLongitude
});
var SOURCEID_LIST_ELEMENT = "sp-sourceid-list";
var CHANNEL_LIST_ELEMENT = "sp-channel-list";
var CHANNEL_CODE_ELEMENT = "sp-channel-code-input";
var MINMAX_ELEMENT = "sp-minmax";
var LATLONRADIUS_ELEMENT = "sp-latlon-radius";
var LATLONBOX_ELEMENT = "sp-latlon-box";
var LATLON_CHOICE_ELEMENT = "sp-latlon-choice";
function numberOrNaN(a) {
  if (a == null) {
    return Number.NaN;
  } else {
    return Number.parseFloat(`${a}`);
  }
}
function numberFromInput(root2, query) {
  if (!root2) {
    throw new Error(`no root`);
  }
  const el = root2.querySelector(query);
  if (el instanceof HTMLInputElement) {
    return Number.parseFloat(el.value);
  } else {
    throw new Error("element is not HTMLInputElement");
  }
}
function labeledTextInput(label, defaultVal, classname = null) {
  const ndiv = document.createElement("span");
  const nlabel = ndiv.appendChild(document.createElement("label"));
  nlabel.textContent = label;
  const ntext = ndiv.appendChild(document.createElement("input"));
  ntext.setAttribute("type", "text");
  ntext.setAttribute("name", label);
  ntext.setAttribute("class", classname ? classname : label);
  ntext.value = defaultVal;
  return ndiv;
}
function labeledNumberInput(label, defaultVal) {
  const ndiv = document.createElement("span");
  const nlabel = ndiv.appendChild(document.createElement("label"));
  nlabel.textContent = label;
  const ntext = ndiv.appendChild(document.createElement("input"));
  ntext.setAttribute("type", "number");
  ntext.setAttribute("name", label);
  ntext.setAttribute("class", label);
  ntext.value = defaultVal;
  return ndiv;
}
var ATTR_NET = "network";
var ATTR_STA = "station";
var ATTR_LOC = "location";
var ATTR_CHAN = "channel";
var ATTR_LIST = [ATTR_NET, ATTR_STA, ATTR_LOC, ATTR_CHAN];
var ChannelCodeInput = class extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: "open" });
    const wrapper = document.createElement("span");
    wrapper.setAttribute("class", "wrapper");
    const net = this.hasAttribute(ATTR_NET) ? stringify(this.getAttribute(ATTR_NET)) : "XX";
    const netIn = wrapper.appendChild(
      labeledTextInput("Network:", net, ATTR_NET)
    );
    netIn.addEventListener(
      "change",
      () => this.dispatchEvent(new Event("change"))
    );
    const sta = this.hasAttribute(ATTR_STA) ? stringify(this.getAttribute(ATTR_STA)) : "";
    const staIn = wrapper.appendChild(
      labeledTextInput("Station:", sta, ATTR_STA)
    );
    staIn.addEventListener(
      "change",
      () => this.dispatchEvent(new Event("change"))
    );
    const loc = this.hasAttribute(ATTR_LOC) ? stringify(this.getAttribute(ATTR_LOC)) : "";
    const locIn = wrapper.appendChild(
      labeledTextInput("Location:", loc, ATTR_LOC)
    );
    locIn.addEventListener(
      "change",
      () => this.dispatchEvent(new Event("change"))
    );
    const chan = this.hasAttribute(ATTR_CHAN) ? stringify(this.getAttribute(ATTR_CHAN)) : "";
    const chanIn = wrapper.appendChild(
      labeledTextInput("Channel:", chan, ATTR_CHAN)
    );
    chanIn.addEventListener(
      "change",
      () => this.dispatchEvent(new Event("change"))
    );
    const style = document.createElement("style");
    style.textContent = `
      .wrapper {
        position: relative;
      }
      input {
        width: 50px;
      }
    `;
    shadow.appendChild(style);
    shadow.appendChild(wrapper);
  }
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === ATTR_NET || name === ATTR_STA || name === ATTR_LOC || name === ATTR_CHAN) {
      this._setInputValue(name, newValue);
    }
  }
  static get observedAttributes() {
    return ATTR_LIST;
  }
  get network() {
    return this._getInputValue(ATTR_NET);
  }
  set network(n2) {
    this._setInputValue(ATTR_NET, n2);
  }
  get station() {
    return this._getInputValue(ATTR_STA);
  }
  set station(n2) {
    this._setInputValue(ATTR_STA, n2);
  }
  get location() {
    return this._getInputValue(ATTR_LOC);
  }
  set location(n2) {
    this._setInputValue(ATTR_LOC, n2);
  }
  get channel() {
    return this._getInputValue(ATTR_CHAN);
  }
  set channel(n2) {
    this._setInputValue(ATTR_CHAN, n2);
  }
  _getInputValue(name) {
    return this.shadowRoot?.querySelector("input." + name)?.value ?? "";
  }
  _setInputValue(name, val) {
    if (this.shadowRoot) {
      this.shadowRoot.querySelector("input." + name).value = val;
    }
  }
};
customElements.define(CHANNEL_CODE_ELEMENT, ChannelCodeInput);
var ChannelListChooser = class extends HTMLElement {
  constructor() {
    super();
    this.selected_channels = /* @__PURE__ */ new Set();
    this.channels = [];
    this.draw_element();
  }
  draw_element() {
    let shadow = this.shadowRoot;
    if (shadow === null) {
      shadow = this.attachShadow({ mode: "open" });
    }
    while (shadow.lastChild) {
      shadow.removeChild(shadow.lastChild);
    }
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    const label = wrapper.appendChild(document.createElement("label"));
    label.textContent = "Channels:";
    this.channels.forEach((c) => {
      const channel = c;
      const div = wrapper.appendChild(document.createElement("div"));
      const cb = div.appendChild(document.createElement("input"));
      cb.setAttribute("type", this.type);
      cb.setAttribute("name", "radiogroup");
      cb.addEventListener("change", () => {
        if (this.type === "radio") {
          this.selected_channels.clear();
          this.selected_channels.add(channel);
        } else {
          if (cb.checked) {
            this.selected_channels.add(channel);
          } else {
            this.selected_channels.delete(channel);
          }
        }
        this.dispatchEvent(new Event("change"));
      });
      const nlabel = div.appendChild(document.createElement("label"));
      nlabel.textContent = `${c.codes()} ${c.startDate.toISO()}`;
    });
    shadow.appendChild(wrapper);
  }
  setChannels(channels) {
    this.channels = channels;
    this.draw_element();
    this.dispatchEvent(new Event("change"));
  }
  appendChannels(channels) {
    this.channels = this.channels.concat(channels);
    this.draw_element();
    this.dispatchEvent(new Event("change"));
  }
  get type() {
    const t = this.getAttribute("type");
    if (t) {
      return t;
    } else {
      return "checkbox";
    }
  }
  set type(s2) {
    if (s2 === "checkbox" || s2 === "radio") {
      this.setAttribute("type", s2);
    } else {
      throw new Error("must be one of checkbox or radio");
    }
  }
  attributeChangedCallback(_name, _oldValue, _newValue) {
    this.draw_element();
  }
  selectedChannels() {
    return Array.from(this.selected_channels.values());
  }
};
customElements.define(CHANNEL_LIST_ELEMENT, ChannelListChooser);
var SourceIdListChooser = class extends HTMLElement {
  constructor() {
    super();
    this.selected_sourceIds = /* @__PURE__ */ new Set();
    this.sourceIdList = [];
    this.draw_element();
  }
  draw_element() {
    let shadow = this.shadowRoot;
    if (shadow === null) {
      shadow = this.attachShadow({ mode: "open" });
    }
    while (shadow.lastChild) {
      shadow.removeChild(shadow.lastChild);
    }
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    const label = wrapper.appendChild(document.createElement("label"));
    label.textContent = "Channels:";
    this.sourceIdList.forEach((c) => {
      const sourceId = c;
      const div = wrapper.appendChild(document.createElement("div"));
      const cb = div.appendChild(document.createElement("input"));
      cb.setAttribute("type", this.type);
      cb.setAttribute("name", "radiogroup");
      cb.addEventListener("change", (_event) => {
        if (this.type === "radio") {
          this.selected_sourceIds.clear();
          this.selected_sourceIds.add(sourceId);
        } else {
          if (cb.checked) {
            this.selected_sourceIds.add(sourceId);
          } else {
            this.selected_sourceIds.delete(sourceId);
          }
        }
        this.dispatchEvent(new Event("change"));
      });
      const nlabel = div.appendChild(document.createElement("label"));
      nlabel.textContent = `${c.toStringNoPrefix()}`;
    });
    shadow.appendChild(wrapper);
  }
  setSourceIds(sourceIdList) {
    this.sourceIdList = sourceIdList;
    this.draw_element();
    this.dispatchEvent(new Event("change"));
  }
  appendSourceIds(sourceIdList) {
    this.sourceIdList = this.sourceIdList.concat(sourceIdList);
    this.draw_element();
    this.dispatchEvent(new Event("change"));
  }
  get type() {
    const t = this.getAttribute("type");
    if (t) {
      return t;
    } else {
      return "checkbox";
    }
  }
  set type(s2) {
    if (s2 === "checkbox" || s2 === "radio") {
      this.setAttribute("type", s2);
    } else {
      throw new Error("must be one of checkbox or radio");
    }
  }
  attributeChangedCallback(_name, _oldValue, _newValue) {
    this.draw_element();
  }
  selectedSourceIds() {
    return Array.from(this.selected_sourceIds.values());
  }
};
customElements.define(SOURCEID_LIST_ELEMENT, SourceIdListChooser);
var LabeledMinMax = class extends HTMLElement {
  constructor() {
    super();
    this.default_min = 0;
    this.default_max = 10;
    this.attachShadow({ mode: "open" });
    this.draw_element();
  }
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === "lowerbound") {
      const lowerbound = numberOrNaN(newValue);
      this.shadowRoot?.querySelector("input.min")?.setAttribute("min", `${lowerbound}`);
      this.shadowRoot?.querySelector("input.max")?.setAttribute("min", `${lowerbound}`);
    }
    if (name === "upperbound") {
      const upperbound = numberOrNaN(newValue);
      this.shadowRoot?.querySelector("input.min")?.setAttribute("max", `${upperbound}`);
      this.shadowRoot?.querySelector("input.max")?.setAttribute("max", `${upperbound}`);
    }
    if (name === "min" && !Number.isNaN(numberOrNaN(newValue))) {
      this.min = numberOrNaN(newValue);
    }
    if (name === "max" && !Number.isNaN(numberOrNaN(newValue))) {
      this.max = numberOrNaN(newValue);
    }
    this.validate();
  }
  static get observedAttributes() {
    return ["lowerbound", "upperbound", "min", "max"];
  }
  draw_element() {
    let shadow = this.shadowRoot;
    if (!shadow) {
      shadow = this.attachShadow({ mode: "open" });
    }
    const minAttr = this.getAttribute("min");
    if (minAttr !== null) {
      this.default_min = Number.parseFloat(minAttr);
    }
    const maxAttr = this.getAttribute("max");
    if (maxAttr !== null) {
      this.default_max = Number.parseFloat(maxAttr);
    }
    let lowerbound = Number.NaN;
    let upperbound = Number.NaN;
    const lbAttr = this.getAttribute("lowerbound");
    if (lbAttr !== null) {
      lowerbound = Number.parseFloat(lbAttr);
    }
    const upAttr = this.getAttribute("upperbound");
    if (upAttr !== null) {
      upperbound = Number.parseFloat(upAttr);
    }
    const style = shadow.appendChild(document.createElement("style"));
    style.textContent = `
      input {
        width: 6em;
      }
      label {
        margin-left: 3px;
        margin-right: 3px;
      }
    `;
    const wrapper = document.createElement("span");
    wrapper.setAttribute("class", "wrapper");
    const min_text = wrapper.appendChild(document.createElement("input"));
    min_text.setAttribute("type", "number");
    min_text.setAttribute("name", "min");
    min_text.setAttribute("class", "min");
    if (lowerbound) {
      min_text.setAttribute("min", `${lowerbound}`);
    }
    if (upperbound) {
      min_text.setAttribute("max", `${upperbound}`);
    }
    min_text.value = `${this.default_min}`;
    min_text.addEventListener("change", () => {
      this.validate("min");
      this.dispatchEvent(new Event("change"));
    });
    const to_label = wrapper.appendChild(document.createElement("label"));
    to_label.textContent = "to";
    const max_text = wrapper.appendChild(document.createElement("input"));
    max_text.setAttribute("type", "number");
    max_text.setAttribute("name", "max");
    max_text.setAttribute("class", "max");
    if (lowerbound) {
      max_text.setAttribute("min", `${lowerbound}`);
    }
    if (upperbound) {
      max_text.setAttribute("max", `${upperbound}`);
    }
    max_text.value = `${this.default_max}`;
    max_text.addEventListener("change", () => {
      this.validate("max");
      this.dispatchEvent(new Event("change"));
    });
    shadow.appendChild(wrapper);
    this.validate("min");
  }
  validate(lastChanged) {
    const lowerbound = numberOrNaN(this.getAttribute("lowerbound"));
    const upperbound = numberOrNaN(this.getAttribute("upperbound"));
    if (!Number.isNaN(lowerbound)) {
      if (this.min < lowerbound) {
        this.min = lowerbound;
      }
      if (this.max < lowerbound) {
        this.max = lowerbound;
      }
    }
    if (!Number.isNaN(upperbound)) {
      if (this.min > upperbound) {
        this.min = upperbound;
      }
      if (this.max > upperbound) {
        this.max = upperbound;
      }
    }
    if (this.min > this.max) {
      if (lastChanged === "max") {
        this.min = this.max;
      } else {
        this.max = this.min;
      }
    }
  }
  get lowerbound() {
    return numberOrNaN(this.getAttribute("lowerbound"));
  }
  set lowerbound(v) {
    this.setAttribute("lowerbound", `${v}`);
  }
  get upperbound() {
    return numberOrNaN(this.getAttribute("upperbound"));
  }
  set upperbound(v) {
    this.setAttribute("upperbound", `${v}`);
  }
  get min() {
    const input = this.shadowRoot?.querySelector(
      "input.min"
    );
    if (input) {
      return Number.parseFloat(input.value);
    } else {
      throw new Error("cant find input.min");
    }
  }
  set min(v) {
    const input = this.shadowRoot?.querySelector(
      "input.min"
    );
    if (input) {
      input.value = v.toString();
    } else {
      throw new Error("cant find input.min");
    }
  }
  get max() {
    const input = this.shadowRoot?.querySelector(
      "input.max"
    );
    if (input) {
      return Number.parseFloat(input.value);
    } else {
      throw new Error("cant find input.max");
    }
  }
  set max(v) {
    const input = this.shadowRoot?.querySelector(
      "input.max"
    );
    if (input) {
      input.value = v.toString();
    } else {
      throw new Error("cant find input.max");
    }
  }
  updateMinMax() {
    const min = numberOrNaN(this.getAttribute("min"));
    if (!Number.isNaN(min)) {
      this.default_min = min;
    }
    const max = numberOrNaN(this.getAttribute("max"));
    if (!Number.isNaN(max)) {
      this.default_max = max;
    }
  }
  connectedCallback() {
    this.updateMinMax();
  }
};
customElements.define(MINMAX_ELEMENT, LabeledMinMax);
function validateLatitude(value) {
  if (Number.isNaN(value)) {
    return 0;
  }
  if (value < -90) {
    return -90;
  }
  if (value > 90) {
    return 90;
  }
  return value;
}
function validateLongitude(value) {
  if (Number.isNaN(value)) {
    return 0;
  }
  if (value < -180) {
    return -180;
  }
  if (value > 360) {
    return 360;
  }
  return value;
}
var LatLonRadiusEl = class extends HTMLElement {
  constructor() {
    super();
    this.draw();
  }
  draw() {
    let shadow = this.shadowRoot;
    if (shadow === null) {
      shadow = this.attachShadow({ mode: "open" });
    }
    while (shadow.lastChild) {
      shadow.removeChild(shadow.lastChild);
    }
    const style = shadow.appendChild(document.createElement("style"));
    style.textContent = `
      input {
        width: 4em;
      }
      label {
        margin-left: 3px;
        margin-right: 3px;
      }
    `;
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    const latDiv = wrapper.appendChild(labeledNumberInput("Lat", "0"));
    const latIn = latDiv.querySelector("input");
    if (!latIn) {
      throw new Error("can't find input");
    }
    latIn.textContent = "Lat: ";
    latIn.setAttribute("min", "-90.0");
    latIn.setAttribute("max", "90.0");
    latIn.addEventListener("change", () => {
      const value = Number.parseFloat(latIn.value);
      if (value !== validateLatitude(value)) {
        latIn.value = `${validateLatitude(value)}`;
      }
      this.dispatchEvent(new Event("change"));
    });
    const lonDiv = wrapper.appendChild(labeledNumberInput("Lon", "0"));
    const lonIn = lonDiv.querySelector("input");
    if (!lonIn) {
      throw new Error("can't find input");
    }
    lonIn.textContent = "Lon: ";
    lonIn.setAttribute("min", "-180.0");
    lonIn.setAttribute("max", "360.0");
    lonIn.addEventListener("change", () => {
      const value = Number.parseFloat(lonIn.value);
      if (value !== validateLongitude(value)) {
        lonIn.value = `${validateLongitude(value)}`;
      }
      this.dispatchEvent(new Event("change"));
    });
    const radius_label = wrapper.appendChild(document.createElement("label"));
    radius_label.textContent = "Radius: ";
    radius_label.setAttribute("for", "radiusminmax");
    const radius_minmax = wrapper.appendChild(new LabeledMinMax());
    radius_label.setAttribute("id", "radiusminmax");
    radius_minmax.setAttribute("lowerbound", "0.0");
    radius_minmax.setAttribute("upperbound", "180.0");
    radius_minmax.min = 0;
    radius_minmax.max = 180;
    radius_minmax.addEventListener(
      "change",
      () => this.dispatchEvent(new Event("change"))
    );
    shadow.appendChild(wrapper);
  }
  attributeChangedCallback(_name, _oldValue, _newValue) {
    this.innerHTML = "";
    this.draw();
  }
  static get observedAttributes() {
    return ["latitude", "longitude", "minradius", "maxradius"];
  }
  get latitude() {
    const inEl = this.shadowRoot?.querySelector(
      "input.Lat"
    );
    return Number.parseFloat(inEl.value);
  }
  set latitude(v) {
    const inEl = this.shadowRoot?.querySelector(
      "input.Lat"
    );
    inEl.value = `${validateLatitude(v)}`;
    this.dispatchEvent(new Event("change"));
  }
  get longitude() {
    const inEl = this.shadowRoot?.querySelector(
      "input.Lon"
    );
    return Number.parseFloat(inEl.value);
  }
  set longitude(v) {
    const inEl = this.shadowRoot?.querySelector(
      "input.Lon"
    );
    inEl.value = `${validateLongitude(v)}`;
    this.dispatchEvent(new Event("change"));
  }
  get minRadius() {
    const mm = this.shadowRoot?.querySelector(MINMAX_ELEMENT);
    if (mm) {
      return mm.min;
    } else {
      throw new Error(`cant find ${MINMAX_ELEMENT}`);
    }
  }
  set minRadius(v) {
    const mm = this.shadowRoot?.querySelector(MINMAX_ELEMENT);
    if (mm) {
      mm.min = v;
      this._doUpdateCallback();
    } else {
      throw new Error(`cant find ${MINMAX_ELEMENT}`);
    }
  }
  get maxRadius() {
    const mm = this.shadowRoot?.querySelector(MINMAX_ELEMENT);
    if (mm) {
      return mm.max;
    } else {
      throw new Error(`cant find ${MINMAX_ELEMENT}`);
    }
  }
  set maxRadius(v) {
    const mm = this.shadowRoot?.querySelector(MINMAX_ELEMENT);
    if (mm) {
      mm.max = v;
      this._doUpdateCallback();
    } else {
      throw new Error(`cant find ${MINMAX_ELEMENT}`);
    }
  }
  asLatLonRadius() {
    return new LatLonRadius(
      this.latitude,
      this.longitude,
      this.minRadius,
      this.maxRadius
    );
  }
  toString() {
    return `LatLon Radius: ${this.latitude}/${this.longitude} ${this.minRadius}/${this.maxRadius}`;
  }
  _doUpdateCallback() {
    this.dispatchEvent(new Event("change"));
  }
};
customElements.define(LATLONRADIUS_ELEMENT, LatLonRadiusEl);
var latlonbox_html = `
<style>
input {
  width: 4em;
}
label {
  margin-right: 2px;
  margin-left: 2px;
}
fieldset.latlon {
  display: grid;
  width: 250px;
  grid-template-columns:  1fr  1fr  1fr  1fr  1fr ;
}
</style>
<fieldset class="latlon">
  <div></div>
  <div></div>
  <div style="text-align: center;">
  <div><label for="north">North</label></div>
    <div><input id="north" type="number"/></div>
  </div>
  <div></div>
  <div></div>
  <div style="text-align: right;">
    <label for="west">West</label>
  </div>
  <div>
    <input id="west" type="number"/></div>
  <div style="text-align: center;margin-top: 2px;"><label>Lat/Lon</label></div>
  <div style="text-align: left;">
    <input id="east" type="number"/>
  </div>
  <div>
    <label for="east">East</label>
  </div>
  <div></div>
  <div></div>
  <div style="text-align: center;">
    <div><input id="south" type="number"/></div>
    <div><label for="south">South</label></div>
  </div>
  <div></div>
  <div></div>
</fieldset>
`;
var LatLonBoxEl = class extends HTMLElement {
  constructor() {
    super();
    this.draw();
  }
  attributeChangedCallback(_name, _oldValue, _newValue) {
    this.innerHTML = "";
    this.draw();
  }
  static get observedAttributes() {
    return ["south", "north", "east", "west"];
  }
  draw() {
    let shadow = this.shadowRoot;
    if (shadow === null) {
      shadow = this.attachShadow({ mode: "open" });
    }
    shadow.innerHTML = latlonbox_html;
    const southEl = shadow.querySelector("input#south");
    if (!southEl) {
      throw new Error("cant find input");
    }
    const southAttr = numberOrNaN(this.getAttribute("south"));
    southEl.value = `${Number.isNaN(southAttr) ? -90 : validateLatitude(southAttr)}`;
    southEl?.addEventListener("change", () => {
      const value = Number.parseFloat(southEl.value);
      if (value !== validateLatitude(value)) {
        southEl.value = `${validateLatitude(value)}`;
      }
      this.validate("south");
      this.dispatchEvent(new Event("change"));
    });
    const northEl = shadow.querySelector("input#north");
    if (!northEl) {
      throw new Error("cant find input");
    }
    const northAttr = numberOrNaN(this.getAttribute("north"));
    northEl.value = `${Number.isNaN(northAttr) ? 90 : validateLatitude(northAttr)}`;
    northEl?.addEventListener("change", () => {
      const value = Number.parseFloat(northEl.value);
      if (value !== validateLatitude(value)) {
        northEl.value = `${validateLatitude(value)}`;
      }
      this.validate("north");
      this.dispatchEvent(new Event("change"));
    });
    const westEl = shadow.querySelector("input#west");
    if (!westEl) {
      throw new Error("cant find input");
    }
    const westAttr = numberOrNaN(this.getAttribute("west"));
    westEl.value = `${Number.isNaN(westAttr) ? -180 : validateLongitude(westAttr)}`;
    westEl?.addEventListener("change", () => {
      const value = Number.parseFloat(westEl.value);
      if (value !== validateLongitude(value)) {
        westEl.value = `${validateLongitude(value)}`;
      }
      this.validate("west");
      this.dispatchEvent(new Event("change"));
    });
    const eastEl = shadow.querySelector("input#east");
    if (!eastEl) {
      throw new Error("cant find input");
    }
    const eastAttr = numberOrNaN(this.getAttribute("east"));
    eastEl.value = `${Number.isNaN(eastAttr) ? 180 : validateLongitude(eastAttr)}`;
    eastEl?.addEventListener("change", () => {
      const value = Number.parseFloat(eastEl.value);
      if (value !== validateLongitude(value)) {
        eastEl.value = `${validateLongitude(value)}`;
      }
      this.validate("east");
      this.dispatchEvent(new Event("change"));
    });
  }
  get south() {
    return numberFromInput(this.shadowRoot, "input#south");
  }
  set south(value) {
    const inputEl = this.shadowRoot?.querySelector(
      "input#south"
    );
    if (!inputEl) {
      throw new Error("can't find input");
    }
    inputEl.value = `${validateLatitude(value)}`;
    this.validate("south");
    this.dispatchEvent(new Event("change"));
  }
  get north() {
    return numberFromInput(this.shadowRoot, "input#north");
  }
  set north(value) {
    const inputEl = this.shadowRoot?.querySelector(
      "input#north"
    );
    if (!inputEl) {
      throw new Error("can't find input");
    }
    inputEl.value = `${validateLatitude(value)}`;
    this.validate("north");
    this.dispatchEvent(new Event("change"));
  }
  get west() {
    return numberFromInput(this.shadowRoot, "input#west");
  }
  set west(value) {
    const inputEl = this.shadowRoot?.querySelector(
      "input#west"
    );
    if (!inputEl) {
      throw new Error("can't find input");
    }
    inputEl.value = `${validateLongitude(value)}`;
    this.validate("west");
    this.dispatchEvent(new Event("change"));
  }
  get east() {
    return numberFromInput(this.shadowRoot, "input#east");
  }
  set east(value) {
    const inputEl = this.shadowRoot?.querySelector(
      "input#east"
    );
    if (!inputEl) {
      throw new Error("can't find input");
    }
    inputEl.value = `${validateLongitude(value)}`;
    this.validate("east");
    this.dispatchEvent(new Event("change"));
  }
  asLatLonBox() {
    return new LatLonBox(this.west, this.east, this.south, this.north);
  }
  validate(lastChanged) {
    if (this.south > this.north) {
      if (lastChanged === "south") {
        this.north = this.south;
      } else {
        this.south = this.north;
      }
    }
    if (this.west > this.east) {
      if (lastChanged === "east") {
        if (this.west > 180 && this.west - 360 < this.east) {
          this.west = this.west - 360;
        } else {
          this.west = this.east;
        }
      } else {
        if (this.east < 0 && this.east + 360 > this.west) {
          this.east = this.east + 360;
        } else {
          this.east = this.west;
        }
      }
    }
  }
  toString() {
    return `LatLon Box: ${this.west}/${this.east}/${this.south}/${this.north}`;
  }
};
customElements.define(LATLONBOX_ELEMENT, LatLonBoxEl);
var latlonchoice_html = `
<style>
label {
}
.labeled {
}
${LATLONRADIUS_ELEMENT} {
  display:inline-block;
}
${LATLONBOX_ELEMENT} {
  display:inline-block;
}
</style>
<div class="top">
  <div class="labeled">
    <input type="radio" id="latlonall" name="latlon" value="all" checked>
    <label for="latlonradius">All: </label>
  </div>
  <div class="labeled">
    <input type="radio" id="latlonradius" name="latlon" value="radius">
    <label for="latlonradius">Radius: </label>
    <${LATLONRADIUS_ELEMENT}></${LATLONRADIUS_ELEMENT}>
  </div>
  <div class="labeled">
    <input type="radio" id="latlonbox" name="latlon" value="box">
    <label for="latlonbox">Box: </label>
    <${LATLONBOX_ELEMENT}></${LATLONBOX_ELEMENT}>
  </div>
</div>
`;
var LatLonChoice = class extends HTMLElement {
  constructor() {
    super();
    this.draw();
  }
  static get observedAttributes() {
    return LatLonBoxEl.observedAttributes.concat(LatLonRadiusEl.observedAttributes).concat(["geochoice"]);
  }
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === "north") {
      this.latLonBox.north = parseFloat(newValue);
    } else if (name === "south") {
      this.latLonBox.south = parseFloat(newValue);
    } else if (name === "east") {
      this.latLonBox.east = parseFloat(newValue);
    } else if (name === "west") {
      this.latLonBox.west = parseFloat(newValue);
    } else if (name === "latitude") {
      this.latLonRadius.latitude = parseFloat(newValue);
    } else if (name === "longitude") {
      this.latLonRadius.longitude = parseFloat(newValue);
    } else if (name === "minradius") {
      this.latLonRadius.minRadius = parseFloat(newValue);
    } else if (name === "maxradius") {
      this.latLonRadius.maxRadius = parseFloat(newValue);
    } else if (name === "geochoice") {
      const shadow = this.shadowRoot;
      if (shadow === null) {
        throw new Error("shadowRoot is null");
      }
      const all = shadow.querySelector("#latlonall");
      const box = shadow.querySelector("#latlonbox");
      const radius = shadow.querySelector("#latlonradius");
      if (all === null || box === null || radius === null) {
        throw new Error("element is null");
      }
      if (newValue === "all") {
        all.checked = true;
        radius.checked = false;
        box.checked = false;
      } else if (newValue === "box") {
        all.checked = false;
        radius.checked = false;
        box.checked = true;
      } else if (newValue === "radius") {
        all.checked = false;
        radius.checked = true;
        box.checked = false;
      }
    } else {
    }
  }
  draw() {
    let shadow = this.shadowRoot;
    if (shadow === null) {
      shadow = this.attachShadow({ mode: "open" });
    }
    shadow.innerHTML = latlonchoice_html;
    this.shadowRoot?.querySelectorAll("input[type=radio]").forEach((inEl) => {
      inEl?.addEventListener("change", () => {
        this.dispatchEvent(new Event("change"));
      });
    });
    this.shadowRoot?.querySelector("sp-latlon-box")?.addEventListener("change", () => {
      this.dispatchEvent(new Event("change"));
    });
    this.shadowRoot?.querySelector("sp-latlon-radius")?.addEventListener("change", () => {
      this.dispatchEvent(new Event("change"));
    });
  }
  /**
   * returns choosen sub element, either LatLonBox or LatLonRadius or
   * null if choosen is "all"
   *
   * @returns choosen element
   */
  choosen() {
    const radio = this.shadowRoot?.querySelector(
      "input[type=radio]:checked"
    );
    if (radio.value === "box") {
      return this.shadowRoot?.querySelector("sp-latlon-box");
    } else if (radio.value === "radius") {
      return this.shadowRoot?.querySelector(
        "sp-latlon-radius"
      );
    } else {
      return null;
    }
  }
  get latLonBox() {
    return this.shadowRoot?.querySelector("sp-latlon-box");
  }
  get latLonRadius() {
    return this.shadowRoot?.querySelector("sp-latlon-radius");
  }
};
customElements.define(LATLON_CHOICE_ELEMENT, LatLonChoice);

// src/dataset.mts
var dataset_exports = {};
__export(dataset_exports, {
  CATALOG_FILE: () => CATALOG_FILE,
  DATASET_DIR: () => DATASET_DIR,
  DOT_ZIP_EXT: () => DOT_ZIP_EXT,
  Dataset: () => Dataset,
  INVENTORY_FILE: () => INVENTORY_FILE,
  SEISMOGRAM_DIR: () => SEISMOGRAM_DIR,
  ZIP_FILENAME: () => ZIP_FILENAME,
  createBagExtraHeaders: () => createBagExtraHeaders,
  createExtraHeaders: () => createExtraHeaders,
  insertExtraHeaders: () => insertExtraHeaders,
  load: () => load,
  loadFromFile: () => loadFromFile,
  loadFromZip: () => loadFromZip,
  mightBeZipFile: () => mightBeZipFile,
  sddFromMSeed3: () => sddFromMSeed3
});

// src/traveltime.mts
var traveltime_exports = {};
__export(traveltime_exports, {
  FAKE_EMPTY_SVG: () => FAKE_EMPTY_SVG,
  FAKE_EMPTY_TEXT_HEADERS: () => FAKE_EMPTY_TEXT_HEADERS,
  FAKE_EMPTY_TEXT_MODEL: () => FAKE_EMPTY_TEXT_MODEL,
  JSON_FORMAT: () => JSON_FORMAT,
  SVG_FORMAT: () => SVG_FORMAT,
  TEXT_FORMAT: () => TEXT_FORMAT,
  TRAVELTIME_SERVICE: () => TRAVELTIME_SERVICE,
  TraveltimeQuery: () => TraveltimeQuery,
  convertTravelTimeLineToObject: () => convertTravelTimeLineToObject,
  createEmptyTraveltimeJson: () => createEmptyTraveltimeJson,
  createOriginArrival: () => createOriginArrival,
  isValidTraveltimeArrivalType: () => isValidTraveltimeArrivalType,
  isValidTraveltimeJsonType: () => isValidTraveltimeJsonType
});
var TEXT_FORMAT = "text";
var JSON_FORMAT = "json";
var SVG_FORMAT = "svg";
var TRAVELTIME_SERVICE = "traveltime";
function isValidTraveltimeJsonType(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  if (!(typeof object2.model === "string" && (typeof object2.sourcedepth === "number" || typeof object2.sourceDepth === "number") && (typeof object2.receiverdepth === "number" || typeof object2.receiverDepth === "number"))) {
    return false;
  }
  if (typeof object2.sourceDepth === "number") {
    object2.sourcedepth = object2.sourceDepth;
    object2.sourceDepth = void 0;
  }
  if (typeof object2.receiverDepth === "number") {
    object2.receiverdepth = object2.receiverDepth;
    object2.receiverDepth = void 0;
  }
  if (!Array.isArray(object2.phases)) {
    return false;
  }
  if (!Array.isArray(object2.arrivals)) {
    return false;
  }
  return true;
}
function isValidTraveltimeArrivalType(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  return typeof object2.distdeg === "number" && typeof object2.name === "string" && typeof object2.time === "number" && typeof object2.rayparam === "number" && typeof object2.takeoff === "number" && typeof object2.incident === "number" && typeof object2.puristdist === "number" && typeof object2.puristname === "string";
}
function convertTravelTimeLineToObject(ttimeline) {
  const items = ttimeline.trim().split(/\s+/);
  return {
    distdeg: parseFloat(items[0]),
    phase: items[2],
    time: parseFloat(items[3]),
    rayparam: parseFloat(items[4]),
    takeoff: parseFloat(items[5]),
    incident: parseFloat(items[6]),
    puristdist: parseFloat(items[7]),
    puristname: items[9]
  };
}
function createOriginArrival(distdeg) {
  return {
    distdeg,
    phase: "origin",
    time: 0,
    rayparam: 0,
    takeoff: 0,
    incident: 0,
    puristdist: distdeg,
    puristname: "origin"
  };
}
var TraveltimeQuery = class extends FDSNCommon {
  constructor(host) {
    if (!isNonEmptyStringArg(host)) {
      host = EARTHSCOPE_HOST;
    }
    super(TRAVELTIME_SERVICE, host);
    this._path_base = IRISWS_PATH_BASE;
    this._evdepth = 0;
    this._format = JSON_FORMAT;
    this._noheader = false;
  }
  protocol(value) {
    doStringGetterSetter(this, "protocol", value);
    return this;
  }
  getProtocol() {
    return this._protocol;
  }
  host(value) {
    doStringGetterSetter(this, "host", value);
    return this;
  }
  getHost() {
    return this._host;
  }
  /**
   * Gets/Sets the remote port to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  port(value) {
    doIntGetterSetter(this, "port", value);
    return this;
  }
  getPort() {
    return this._port;
  }
  pathBase(value) {
    doStringGetterSetter(this, "path_base", value);
    return this;
  }
  getPathBase() {
    return this._path_base;
  }
  /**
   * Gets/Sets the nodata parameter, usually 404 or 204 (default), controlling
   * the status code when no matching data is found by the service.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  nodata(value) {
    doIntGetterSetter(this, "nodata", value);
    return this;
  }
  getNodata() {
    return this._nodata;
  }
  specVersion(value) {
    doStringGetterSetter(this, "specVersion", value);
    return this;
  }
  getSpecVersion() {
    return this._specVersion;
  }
  evdepth(value) {
    doFloatGetterSetter(this, "evdepth", value);
    return this;
  }
  evdepthInMeter(value) {
    doFloatGetterSetter(this, "evdepth", isDef(value) ? value / 1e3 : value);
    return this;
  }
  getEvdepth() {
    return this._evdepth;
  }
  distdeg(value) {
    if (typeof value === "number") {
      this._distdeg = [value];
    } else {
      this._distdeg = value;
    }
    return this;
  }
  getDistdeg() {
    return this._distdeg;
  }
  model(value) {
    doStringGetterSetter(this, "model", value);
    return this;
  }
  getModel() {
    return this._model;
  }
  phases(value) {
    doStringGetterSetter(this, "phases", value);
    return this;
  }
  getPhases() {
    return this._phases;
  }
  stalat(value) {
    doFloatGetterSetter(this, "stalat", value);
    return this;
  }
  getStalat() {
    return this._stalat;
  }
  stalon(value) {
    doFloatGetterSetter(this, "stalon", value);
    return this;
  }
  getStalon() {
    return this._stalon;
  }
  latLonFromStation(station) {
    this.stalat(station.latitude);
    this.stalon(station.longitude);
    return this;
  }
  receiverdepth(value) {
    doFloatGetterSetter(this, "receiverdepth", value);
    return this;
  }
  receiverdepthInMeter(value) {
    doFloatGetterSetter(
      this,
      "receiverdepth",
      isDef(value) ? value / 1e3 : value
    );
    return this;
  }
  receiverdepthFromChannel(channel) {
    return this.receiverdepth(channel.depth / 1e3);
  }
  getReceiverdepth() {
    return this._receiverdepth;
  }
  evlat(value) {
    doFloatGetterSetter(this, "evlat", value);
    return this;
  }
  getEvlat() {
    return this._evlat;
  }
  evlon(value) {
    doFloatGetterSetter(this, "evlon", value);
    return this;
  }
  getEvlon() {
    return this._evlon;
  }
  latLonFromQuake(quake) {
    this.evlat(quake.latitude);
    this.evlon(quake.longitude);
    this.evdepthInMeter(quake.depth);
    return this;
  }
  format(value) {
    doStringGetterSetter(this, "format", value);
    return this;
  }
  getFormat() {
    return this._format;
  }
  noheader(value) {
    doBoolGetterSetter(this, "noheader", value);
    return this;
  }
  getNoheader() {
    return this._noheader;
  }
  /**
   * Get/Set the timeout in seconds for the request. Default is 30.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  timeout(value) {
    doFloatGetterSetter(this, "timeoutSec", value);
    return this;
  }
  getTimeout() {
    return this._timeoutSec;
  }
  queryVersion() {
    const url2 = this.formVersionURL();
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.ok) {
        return response.text();
      } else {
        throw new Error(
          "Fetching over network was not ok: " + response.status + " " + response.statusText
        );
      }
    });
  }
  formVersionURL() {
    return appendToPath(this.formBaseURL(), "version");
  }
  queryText() {
    this.format(TEXT_FORMAT);
    const url2 = this.formURL();
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then(
      (response) => {
        if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
          return FAKE_EMPTY_TEXT_MODEL + (isDef(this._model) ? this.getModel() : "") + FAKE_EMPTY_TEXT_HEADERS;
        } else {
          return response.text();
        }
      }
    );
  }
  queryJson() {
    this.format(JSON_FORMAT);
    const url2 = this.formURL();
    const fetchInit = defaultFetchInitObj(JSON_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
        return createEmptyTraveltimeJson(this);
      } else {
        return response.json();
      }
    }).then((jsonValue) => {
      if (isValidTraveltimeJsonType(jsonValue)) {
        return jsonValue;
      } else {
        throw new TypeError(`Oops, we did not get root traveltime JSON!`);
      }
    });
  }
  querySvg() {
    this.format(SVG_FORMAT);
    const url2 = this.formURL();
    const fetchInit = defaultFetchInitObj(SVG_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 200) {
        return response.text();
      } else if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
        return FAKE_EMPTY_SVG;
      } else {
        throw new Error(`Status not successful: ${response.status}`);
      }
    }).then(function(rawXmlText) {
      return new DOMParser().parseFromString(rawXmlText, SVG_MIME);
    }).then((xml) => {
      const elArray = xml.getElementsByTagName("svg");
      if (elArray.length > 0) {
        return elArray[0];
      } else {
        throw new Error("Can't find svg element in response");
      }
    });
  }
  queryWadl() {
    return fetch(this.formWadlURL()).then((response) => {
      if (response.ok) {
        return response.text().then(
          (textResponse) => new window.DOMParser().parseFromString(textResponse, "text/xml")
        );
      } else {
        throw new Error(
          `Fetching over network was not ok: ${response.status} ${response.statusText}`
        );
      }
    });
  }
  query() {
    if (this._format === JSON_FORMAT) {
      return this.queryJson();
    } else if (this._format === SVG_FORMAT) {
      return this.querySvg();
    } else if (this._format === TEXT_FORMAT) {
      return this.queryText();
    } else {
      throw new Error("Unknown format: " + this._format);
    }
  }
  /**
   * Forms the basic URL to contact the web service, without any query paramters
   *
   * @returns the url
   */
  formBaseURL() {
    let colon = ":";
    const protocol = protocolForKnownHost(this._host, this._protocol);
    if (protocol.endsWith(colon)) {
      colon = "";
    }
    const port = this.defaultPortStringForProtocol(protocol);
    const path2 = `${this._path_base}/${this._service}/${this._specVersion}`;
    return `${protocol}${colon}//${this._host}${port}/${path2}`;
  }
  formURL() {
    let url2 = appendToPath(this.formBaseURL(), "query?");
    if (isDef(this._noheader) && this._noheader) {
      url2 = url2 + "noheader=true&";
    }
    if (isDef(this._evdepth) && this._evdepth !== 0) {
      url2 = url2 + makeParam("evdepth", this._evdepth);
    }
    if (isDef(this._receiverdepth) && this._receiverdepth !== 0) {
      url2 = url2 + makeParam("receiverdepth", this._receiverdepth);
    }
    if (isDef(this._stalat) && isDef(this._stalon)) {
      url2 = url2 + makeParam(
        "staloc",
        "[" + stringify(this._stalat) + "," + stringify(this._stalon) + "]"
      );
    }
    if (isDef(this._evlat) && isDef(this._evlon)) {
      url2 = url2 + makeParam(
        "evloc",
        "[" + stringify(this._evlat) + "," + stringify(this._evlon) + "]"
      );
    }
    if (isDef(this._distdeg)) {
      url2 = url2 + makeParam("distdeg", this._distdeg.join(","));
    }
    if (isDef(this._model)) {
      url2 = url2 + makeParam("model", this._model);
    }
    if (isDef(this._phases)) {
      url2 = url2 + makeParam("phases", this._phases);
    }
    if (isDef(this._format)) {
      url2 = url2 + makeParam("format", this._format);
    }
    if (isDef(this._nodata)) {
      url2 = url2 + makeParam("nodata", this._nodata);
    }
    if (url2.endsWith("&") || url2.endsWith("?")) {
      url2 = url2.substr(0, url2.length - 1);
    }
    return url2;
  }
  queryTauPVersion() {
    const url2 = this.formTauPVersionURL();
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.ok) {
        return response.text();
      } else {
        throw new Error(
          "Fetching over network was not ok: " + response.status + " " + response.statusText
        );
      }
    });
  }
  formTauPVersionURL() {
    return appendToPath(this.formBaseURL(), "taupversion");
  }
  formWadlURL() {
    return appendToPath(this.formBaseURL(), "application.wadl");
  }
};
var FAKE_EMPTY_TEXT_MODEL = `Model: `;
var FAKE_EMPTY_TEXT_HEADERS = `
Distance   Depth   Phase   Travel    Ray Param  Takeoff  Incident  Purist    Purist
  (deg)     (km)   Name    Time (s)  p (s/deg)   (deg)    (deg)   Distance   Name
-----------------------------------------------------------------------------------
`;
function createEmptyTraveltimeJson(ttquery) {
  const out = {
    model: isDef(ttquery._model) ? ttquery._model : "",
    sourcedepth: isDef(ttquery._evdepth) ? ttquery._evdepth : 0,
    receiverdepth: isDef(ttquery._receiverdepth) ? ttquery._receiverdepth : 0,
    phases: isDef(ttquery._phases) ? ttquery._phases.split(",") : [],
    arrivals: []
  };
  return out;
}
var FAKE_EMPTY_SVG = `
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg" width="500" height="500" viewBox="0 0 14016.2 14016.2">
<!--
 This script will plot ray paths generated by TauP using SVG. -->
<defs>
    <style type="text/css"><![CDATA[
        circle {
            vector-effect: non-scaling-stroke;
            stroke: grey;
            fill: none;
        }
        polyline {
            vector-effect: non-scaling-stroke;
            stroke: black;
            fill: none;
        }
    ]]></style>
</defs>
<g transform="translate(7008.1,7008.1)" >
<!-- draw surface and label distances.-->
<!-- tick marks every 30 degrees.-->
  <polyline points="    0.00  -6371.00,     0.00  -6689.55" />
  <polyline points=" 3185.50  -5517.45,  3344.78  -5793.32" />
  <polyline points=" 5517.45  -3185.50,  5793.32  -3344.77" />
  <polyline points=" 6371.00      0.00,  6689.55      0.00" />
  <polyline points=" 5517.45   3185.50,  5793.32   3344.77" />
  <polyline points=" 3185.50   5517.45,  3344.78   5793.32" />
  <polyline points="    0.00   6371.00,     0.00   6689.55" />
  <polyline points="-3185.50   5517.45, -3344.77   5793.32" />
  <polyline points="-5517.45   3185.50, -5793.32   3344.77" />
  <polyline points="-6371.00      0.00, -6689.55      0.00" />
  <polyline points="-5517.45  -3185.50, -5793.32  -3344.78" />
  <polyline points="-3185.50  -5517.45, -3344.78  -5793.32" />
  <circle cx="0.0" cy="0.0" r="6371.0" />
  </g>
</svg>
`;

// src/dataset.mts
var import_jszip = __toESM(require_jszip_min(), 1);
var DATASET_DIR = "dataset";
var DOT_ZIP_EXT = ".zip";
var ZIP_FILENAME = DATASET_DIR + DOT_ZIP_EXT;
var SEISMOGRAM_DIR = "seismograms";
var CATALOG_FILE = "catalog.quakeml";
var INVENTORY_FILE = "inventory.staxml";
var Dataset = class _Dataset {
  constructor() {
    this.name = "dataset";
    this.catalog = new Array(0);
    this.inventory = new Array(0);
    this.waveforms = new Array(0);
    this.processedWaveforms = new Array(0);
    this.extra = /* @__PURE__ */ new Map();
  }
  async saveToZipFile(filename = ZIP_FILENAME) {
    let dirname = DATASET_DIR;
    if (filename.endsWith(DOT_ZIP_EXT)) {
      dirname = filename.slice(0, -4);
    }
    const zipfile = new import_jszip.default();
    const zip = zipfile.folder(dirname);
    if (!zip) {
      throw new Error("unable to create subfolder in zip file: " + dirname);
    }
    const seisFolder = zip.folder(SEISMOGRAM_DIR);
    if (seisFolder === null) {
      throw new Error("can't make folder");
    }
    for (const [key, val] of this.waveformsToMSeed3()) {
      seisFolder.file(key, val);
    }
    const content = await zipfile.generateAsync({
      type: "uint8array",
      compression: "DEFLATE"
    });
    downloadBlobAsFile(content, filename);
  }
  waveformsToMSeed3() {
    const out = /* @__PURE__ */ new Map();
    const ext = "ms3";
    this.waveforms.forEach((sdd) => {
      if (sdd.seismogram) {
        const mseed3Records = toMSeed3(
          sdd.seismogram,
          createBagExtraHeaders(sdd)
        );
        const byteSize = mseed3Records.reduce(
          (acc, cur) => acc + cur.calcSize(),
          0
        );
        const outBuf = new ArrayBuffer(byteSize);
        let offset2 = 0;
        mseed3Records.forEach((ms3Rec) => {
          const recSize = ms3Rec.calcSize();
          const dv = new DataView(outBuf, offset2, recSize);
          ms3Rec.save(dv);
          offset2 += recSize;
        });
        let i = 1;
        let seisId;
        if (!!sdd.id && sdd.id.length > 0) {
          seisId = sdd.id;
        } else {
          seisId = sdd.codes();
        }
        let filename = `${seisId}.${ext}`;
        if (out.has(filename)) {
          seisId = `${seisId}_${sdd.startTime.year}-${sdd.startTime.month}-${sdd.startTime.day}`;
        }
        while (out.has(filename)) {
          i += 1;
          filename = `${seisId}_${i}.${ext}`;
        }
        out.set(filename, outBuf);
      }
    });
    return out;
  }
  merge(other) {
    const out = new _Dataset();
    out.waveforms = this.waveforms.concat(other.waveforms);
    out.inventory = this.inventory.concat(other.inventory);
    out.catalog = this.catalog.concat(other.catalog);
    return out;
  }
  associateQuakes(timeOverlapSecs = 1800) {
    this.waveforms.forEach((w) => {
      if (!w.hasQuake()) {
        this.catalog.forEach((q) => {
          if (q.hasPreferredOrigin()) {
            if (q.preferredOrigin?.time) {
              const dur = Duration.fromMillis(1e3 * timeOverlapSecs);
              const twindow = startDuration(q.preferredOrigin?.time, dur);
              if (twindow.overlaps(w.timeRange)) {
                w.addQuake(q);
              }
            }
          }
        });
      }
    });
  }
  associateChannels() {
    this.waveforms.forEach((sdd) => {
      if (!sdd.hasChannel()) {
        for (const c of allChannels(this.inventory)) {
          if (c.sourceId.equals(sdd.sourceId) && sdd.timeRange.overlaps(c.timeRange)) {
            sdd.channel = c;
            break;
          }
        }
      }
    });
  }
};
function load(url2) {
  const fetchInitOptions = defaultFetchInitObj(BINARY_MIME);
  return doFetchWithTimeout(url2, fetchInitOptions).then(function(response) {
    if (response.status === 200 || response.status === 0) {
      return response.blob();
    } else {
      throw new Error("No data");
    }
  }).then((data) => import_jszip.default.loadAsync(data)).then((zip) => loadFromZip(zip));
}
async function loadFromFile(file2) {
  const zip = await new import_jszip.default().loadAsync(file2);
  return loadFromZip(zip);
}
async function loadFromZip(zip) {
  const promiseArray = new Array(0);
  let datasetDir;
  const possibleDirs = zip.folder(new RegExp("/" + SEISMOGRAM_DIR));
  if (possibleDirs.length === 0) {
    throw new Error("Unable to find dataset directory in zip file");
  } else {
    const tmpdatasetDir = zip.folder(
      possibleDirs[0].name.slice(0, -1 * (SEISMOGRAM_DIR.length + 1))
    );
    if (tmpdatasetDir === null) {
      throw new Error("Unable to find dataset directory in zip file");
    } else {
      datasetDir = tmpdatasetDir;
    }
    const seisDir = datasetDir.folder(SEISMOGRAM_DIR);
    if (isDef(seisDir)) {
      seisDir.forEach(function(relativePath, file2) {
        if (file2.name.endsWith(".ms3")) {
          const seisPromise = file2.async("arraybuffer").then(function(buffer) {
            const ms3records = parseMSeed3Records(buffer);
            return sddPerChannel(ms3records);
          });
          promiseArray.push(seisPromise);
        }
      });
    }
  }
  const sddListList = await Promise.all(promiseArray);
  const sddList_1 = sddListList.reduce(
    (acc, sddList) => acc.concat(sddList),
    new Array(0)
  );
  const catalogFile = datasetDir.file(CATALOG_FILE);
  const qml = catalogFile ? catalogFile.async("string").then(function(rawXmlText) {
    if (rawXmlText.length === 0) {
      return [];
    } else if (rawXmlText.length < 10) {
      throw new Error(`qml text is really short: ${rawXmlText}`);
    } else {
      const rawXml = new DOMParser().parseFromString(rawXmlText, XML_MIME);
      return parseQuakeML(rawXml).eventList;
    }
  }) : Promise.resolve([]);
  const inventoryFile = datasetDir.file(INVENTORY_FILE);
  const staml = inventoryFile ? inventoryFile.async("string").then(function(rawXmlText_1) {
    if (rawXmlText_1.length === 0) {
      return [];
    } else if (rawXmlText_1.length < 10) {
      throw new Error(`staxml text is really short: ${rawXmlText_1}`);
    } else {
      const rawXml_2 = new DOMParser().parseFromString(
        rawXmlText_1,
        XML_MIME
      );
      return parseStationXml(rawXml_2);
    }
  }) : Promise.resolve([]);
  const promises = await Promise.all([Promise.resolve(sddList_1), qml, staml]);
  const dataset = new Dataset();
  dataset.waveforms = promises[0];
  dataset.catalog = promises[1];
  dataset.inventory = promises[2];
  dataset.associateChannels();
  dataset.associateQuakes();
  return dataset;
}
function sddFromMSeed3(ms3records, ds) {
  const out = [];
  const byChannelMap = byChannel2(ms3records);
  byChannelMap.forEach((ms3segments) => {
    const seis = merge2(ms3segments);
    const sdd = SeismogramDisplayData.fromSeismogram(seis);
    ms3segments.forEach((msr) => {
      insertExtraHeaders(msr.extraHeaders, sdd, "spjs", ds);
    });
    out.push(sdd);
  });
  return out;
}
function insertExtraHeaders(eh, sdd, key, ds) {
  const myEH = extractBagEH(eh);
  if (!myEH) {
    return;
  }
  const quake = ehToQuake(myEH);
  if (quake) {
    sdd.addQuake(quake);
  }
  sdd.addMarkers(ehToMarkers(myEH));
  if (typeof myEH === "object") {
    if ("quake" in myEH) {
      const qList = myEH["quake"];
      if (qList && Array.isArray(qList)) {
        for (const pid of qList) {
          if (ds) {
            for (const q of ds.catalog) {
              if (q.publicId === pid) {
                sdd.addQuake(q);
              }
            }
          } else {
            qList.forEach((q) => sdd.addQuakeId(q));
          }
        }
      }
    }
    if ("traveltimes" in myEH && Array.isArray(myEH["traveltimes"])) {
      for (const tt of myEH["traveltimes"]) {
        if (isValidTraveltimeArrivalType(tt)) {
          sdd.traveltimeList.push(tt);
        }
      }
    }
    if ("markers" in myEH && Array.isArray(myEH["markers"])) {
      const markers = myEH["markers"];
      markers.forEach((m) => {
        if (m && typeof m === "object") {
          if ("time" in m && typeof m.time === "string") {
            m.time = isoToDateTime(m.time);
          }
          if (isValidMarker(m)) {
            sdd.markerList.push(m);
          }
        }
      });
    }
  }
}
function createBagExtraHeaders(sdd) {
  const out = {};
  const bag = createBagEH();
  if (sdd.quakeList && sdd.quakeList.length > 0) {
    bag.ev = quakeToEH(sdd.quakeList[0]);
  }
  if (sdd.traveltimeList && sdd.traveltimeList.length > 0) {
    out["traveltimes"] = sdd.traveltimeList;
  }
  if (sdd.markerList && sdd.markerList.length > 0) {
    bag.mark = sdd.markerList.map(markerToEH);
  }
  out.bag = bag;
  return out;
}
function createExtraHeaders(key, sdd) {
  const h = {};
  const out = {};
  out[key] = h;
  if (sdd.quakeList && sdd.quakeList.length > 0) {
    h["quake"] = sdd.quakeList.map((q) => q.publicId);
  }
  if (sdd.traveltimeList && sdd.traveltimeList.length > 0) {
    h["traveltimes"] = sdd.traveltimeList;
  }
  if (sdd.markerList && sdd.markerList.length > 0) {
    h["markers"] = sdd.markerList;
  }
  return out;
}
function mightBeZipFile(buf) {
  const dataView = new DataView(buf);
  if (!(dataView.getUint8(0) === 80 && dataView.getUint8(1) === 75 && dataView.getUint8(2) === 3 && dataView.getUint8(3) === 4)) {
    return false;
  }
  return true;
}

// src/datechooser.mts
var datechooser_exports = {};
__export(datechooser_exports, {
  CLOCK_ELEMENT: () => CLOCK_ELEMENT,
  Clock: () => Clock,
  DATETIME_ELEMENT: () => DATETIME_ELEMENT,
  DEFAULT_DUR_LABEL: () => DEFAULT_DUR_LABEL,
  DEFAULT_END_LABEL: () => DEFAULT_END_LABEL,
  DEFAULT_START_LABEL: () => DEFAULT_START_LABEL,
  DURATION_CHANGED: () => DURATION_CHANGED,
  DUR_LABEL: () => DUR_LABEL,
  DateTimeChooser: () => DateTimeChooser,
  END_CHANGED: () => END_CHANGED,
  END_LABEL: () => END_LABEL,
  HOURMIN_ELEMENT: () => HOURMIN_ELEMENT,
  HOUR_MIN_24: () => HOUR_MIN_24,
  HourMinChooser: () => HourMinChooser,
  PREV_NEXT: () => PREV_NEXT,
  START_CHANGED: () => START_CHANGED,
  START_LABEL: () => START_LABEL,
  TIMERANGE_ELEMENT: () => TIMERANGE_ELEMENT,
  TimeRangeChooser: () => TimeRangeChooser,
  extractDuration: () => extractDuration,
  hourMinRegEx: () => hourMinRegEx
});
var CLOCK_ELEMENT = "sp-clock";
var HOURMIN_ELEMENT = "sp-hourmin";
var DATETIME_ELEMENT = "sp-datetime";
var TIMERANGE_ELEMENT = "sp-timerange";
var hourMinRegEx = /^([0-1]?[0-9]):([0-5]?[0-9])$/;
var HOUR_MIN_24 = "HH:mm";
var START_LABEL = "startlabel";
var DEFAULT_START_LABEL = "Start:";
var END_LABEL = "endlabel";
var DEFAULT_END_LABEL = "End:";
var DUR_LABEL = "durLabel";
var DEFAULT_DUR_LABEL = "Dur:";
var PREV_NEXT = "prev-next";
var Clock = class extends HTMLElement {
  constructor() {
    super();
    this.dateFormat = "yyyy-MM-dd HH:mm:ss";
    this.updateMillis = 500;
    this._time = DateTime.utc().set({ millisecond: 0 });
    const shadow = this.attachShadow({ mode: "open" });
    const wrapper = document.createElement("span");
    shadow.appendChild(wrapper);
    wrapper.textContent = this._time.toFormat(this.dateFormat);
    this._updater = setInterval(() => {
      this.updateNow();
    }, this.updateMillis);
  }
  updateNow() {
    this._time = DateTime.utc().set({ millisecond: 0 });
    const el = this.shadowRoot?.querySelector("span");
    if (el) {
      const date6 = this._time.toFormat(this.dateFormat);
      if (el.textContent !== date6) {
        el.textContent = date6;
      }
    }
  }
};
customElements.define(CLOCK_ELEMENT, Clock);
var HourMinChooser = class extends HTMLElement {
  constructor() {
    super();
    this._time = DateTime.utc().set({ second: 0, millisecond: 0 });
    const attr_date_time = this.getAttribute("date-time");
    if (attr_date_time) {
      this._time = isoToDateTime(attr_date_time);
      this._time.set({ second: 0, millisecond: 0 });
    }
    this.updateCallback = function(_time) {
    };
    const shadow = this.attachShadow({ mode: "open" });
    const style = document.createElement("style");
    style.textContent = `
      .hourminpopup {
        position: absolute;
        top: 17px;
        box-shadow: 0 5px 15px -5px rgba(0,0,0,.5);
        background-color: white;
        z-index: 10;
      }
      .hidden {
        visibility: hidden;
      }
      .shown {
        visibility: visible;
      }
      .popupDivRel {
        position: relative;
      }
      input.hourMin {
        width: 4em;
      }
    `;
    shadow.appendChild(style);
    const wrapper = document.createElement("span");
    document.addEventListener("click", (_e) => {
      this.hide();
    });
    const popupDiv = document.createElement("div");
    this.popupDiv = popupDiv;
    popupDiv.setAttribute("class", "hourminpopup hidden");
    const hourDiv = popupDiv.appendChild(document.createElement("div"));
    const hour_label = hourDiv.appendChild(document.createElement("label"));
    hour_label.textContent = "Hour:";
    const hour_slider = hourDiv.appendChild(document.createElement("input"));
    hour_slider.setAttribute("type", "range");
    hour_slider.setAttribute("min", "0");
    hour_slider.setAttribute("max", "23");
    hour_slider.value = `${this.time.hour}`;
    hour_slider.setAttribute("class", "hourSlider");
    hour_slider.oninput = (e) => {
      if (e.target !== null) {
        const target = e.target;
        const hour = Number.parseInt(target.value);
        if (!Number.isNaN(hour)) {
          this.time = this.time.set({ hour });
        }
      }
    };
    const minDiv = popupDiv.appendChild(document.createElement("div"));
    const min_label = minDiv.appendChild(document.createElement("label"));
    min_label.textContent = "Min:";
    const min_slider = minDiv.appendChild(document.createElement("input"));
    min_slider.setAttribute("type", "range");
    min_slider.setAttribute("min", "0");
    min_slider.setAttribute("max", "59");
    min_slider.value = `${this.time.minute}`;
    min_slider.setAttribute("class", "minSlider");
    min_slider.oninput = (e) => {
      if (e.target !== null) {
        const target = e.target;
        const min = Number.parseInt(target.value);
        if (!Number.isNaN(min)) {
          this.time = this.time.set({ minute: min });
        }
      }
    };
    const ntextSpan = wrapper.appendChild(document.createElement("span"));
    const relDiv = ntextSpan.appendChild(document.createElement("span"));
    relDiv.setAttribute("class", "popupDivRel");
    relDiv.appendChild(popupDiv);
    const ntext = ntextSpan.appendChild(document.createElement("input"));
    ntext.setAttribute("type", "text");
    ntext.setAttribute("name", "hourMin");
    ntext.setAttribute("class", "hourMin");
    ntext.value = this.time.toFormat(HOUR_MIN_24);
    ntext.onchange = (_e) => {
      let val = ntext.value;
      if (val === null) {
        val = this.time.toFormat(HOUR_MIN_24);
        ntext.value = val;
      }
      const match2 = hourMinRegEx.exec(val);
      if (match2) {
        const h = match2[1];
        const m = match2[2];
        const newTime = this.time.set({
          hour: parseInt(h),
          minute: parseInt(m)
        });
        if (newTime !== this.time) {
          this.time = newTime;
        }
        this.hide();
      } else {
        ntext.value = this.time.toFormat(HOUR_MIN_24);
      }
    };
    ntext.onclick = (e) => {
      e.stopPropagation();
      this.showHide();
    };
    shadow.appendChild(wrapper);
  }
  /**
   * Shows or hides the popup based on current visibility style
   */
  showHide() {
    if (this.popupDiv.getAttribute("class")?.includes("hidden")) {
      this.show();
    } else {
      this.hide();
    }
  }
  hide() {
    if (!this.popupDiv.getAttribute("class")?.includes("hidden")) {
      this.popupDiv.setAttribute("class", "hourminpopup hidden");
    }
  }
  show() {
    this.popupDiv.setAttribute("class", "hourminpopup visible");
    this._adjustPopupPosition();
  }
  /** @private */
  xxx_adjustPopupPosition() {
    const left2 = 0;
    const top2 = 0;
    this.popupDiv.setAttribute("style", `{left: ${left2} px; top: ${top2} px;}`);
  }
  /** @private */
  _adjustPopupPosition() {
    const hourMinField = this.shadowRoot?.querySelector(
      "input.hourMin"
    );
    const width = hourMinField.offsetWidth;
    const height = hourMinField.offsetHeight;
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;
    const scrollTop = window.pageYOffset;
    let left2 = hourMinField.offsetLeft;
    let top2 = hourMinField.offsetTop + hourMinField.offsetHeight;
    let parentField = hourMinField.offsetParent;
    while (parentField !== null) {
      if (parentField instanceof HTMLElement) {
        left2 += parentField.offsetLeft;
        top2 += parentField.offsetTop;
        parentField = parentField.offsetParent;
      }
    }
    if (left2 + width > viewportWidth) {
      left2 = left2 - width + hourMinField.offsetWidth;
    }
    if (top2 + height > viewportHeight + scrollTop) {
      top2 = top2 - height - hourMinField.offsetHeight;
    }
    this.popupDiv.setAttribute(
      "style",
      `{position: absolute; left: ${left2} px; top: ${top2} px; }`
    );
  }
  /**
   * Get hours and minutes as Duration instead of as a DateTime. Useful for
   * relative times.
   *
   * @returns hours, minutes as Duration
   */
  get asDuration() {
    return Duration.fromObject({
      hours: this.time.hour,
      minutes: this.time.minute
    });
  }
  get time() {
    return this._time;
  }
  set time(dt) {
    this._internalSetTime(dt);
    this.updateCallback(this.time);
    this.dispatchEvent(new Event("change"));
  }
  _internalSetTime(dt) {
    this._time = dt;
    const ntext = this.shadowRoot?.querySelector(
      "input.hourMin"
    );
    ntext.value = this._time.toFormat(HOUR_MIN_24);
    const hourSlider = this.popupDiv?.querySelector(
      "input.hourSlider"
    );
    hourSlider.value = `${this._time.hour}`;
    const minuteSlider = this.popupDiv?.querySelector(
      "input.minSlider"
    );
    minuteSlider.value = `${this._time.minute}`;
  }
};
customElements.define(HOURMIN_ELEMENT, HourMinChooser);
var DateTimeChooser = class extends HTMLElement {
  constructor(time3) {
    super();
    const attr_date_time = this.getAttribute("date-time");
    if (time3) {
      this._time = time3;
      this.setAttribute("date-time", stringify(time3.toISO()));
    } else if (attr_date_time) {
      this._time = isoToDateTime(attr_date_time);
      this._time.set({ second: 0, millisecond: 0 });
    } else {
      this._time = DateTime.utc().set({ second: 0, millisecond: 0 });
    }
    this.updateCallback = function(_time) {
    };
    const shadow = this.attachShadow({ mode: "open" });
    const wrapper = document.createElement("span");
    const dateField = wrapper.appendChild(document.createElement("input"));
    dateField.setAttribute("type", "date");
    dateField.setAttribute("name", "date");
    dateField.setAttribute("class", "date");
    dateField.value = stringify(this._time.toISODate());
    const hourMin = wrapper.appendChild(new HourMinChooser());
    hourMin._time = this.time;
    this.hourMin = hourMin;
    hourMin.addEventListener("change", () => {
      const origTime = this._time;
      const time4 = hourMin.time;
      if (origTime !== time4) {
        this._internalSetTime(time4);
        this.timeModified();
      }
    });
    dateField.addEventListener("change", () => {
      const value = dateField.value;
      const pikaValue = DateTime.fromISO(value);
      const origTime = this._time;
      if (pikaValue && (origTime.year !== pikaValue.year || origTime.month !== pikaValue.month || origTime.day !== pikaValue.day)) {
        this.time = this.time.set({
          year: pikaValue.year,
          month: pikaValue.month,
          day: pikaValue.day
        });
        this.timeModified();
      }
    });
    shadow.appendChild(wrapper);
    this._internalSetTime(this.time);
  }
  /**
   * Updates the time without triggering the callback function.
   *
   * @param  newTime new time to update sliders
   */
  updateTime(newTime) {
    this._internalSetTime(newTime);
  }
  /**
   * triggers the callback function.
   */
  timeModified() {
    this.updateCallback(this.time);
    this.dispatchEvent(new Event("change"));
  }
  get time() {
    return this._time;
  }
  set time(dt) {
    this._internalSetTime(dt);
    this.updateCallback(this.time);
    this.dispatchEvent(new Event("change"));
  }
  /**
   * internal time set
   *
   * @private
   * @param  newTime new time to update
   */
  _internalSetTime(newTime) {
    this._time = newTime;
    const ntext = this.shadowRoot?.querySelector(
      "input.date"
    );
    ntext.value = stringify(this.time.toISODate());
    this.hourMin._internalSetTime(newTime);
  }
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === "date-time") {
      this.time = isoToDateTime(newValue);
    }
  }
  static get observedAttributes() {
    return ["date-time"];
  }
};
customElements.define(DATETIME_ELEMENT, DateTimeChooser);
var START_CHANGED = "start";
var END_CHANGED = "end";
var DURATION_CHANGED = "duration";
var TimeRangeChooser = class extends HTMLElement {
  constructor() {
    super();
    this._mostRecentChanged = "end";
    this.updateCallback = (_timerange) => {
    };
    const endAttr = this.getAttribute("end");
    let endTime;
    if (endAttr) {
      endTime = isoToDateTime(endAttr);
    } else {
      endTime = DateTime.utc().startOf("minute");
    }
    const durAttr = this.getAttribute("duration");
    if (durAttr) {
      this._duration = extractDuration(durAttr);
    } else {
      this._duration = Duration.fromMillis(1e3 * 300);
    }
    const startAttr = this.getAttribute("start");
    let startTime;
    if (startAttr) {
      startTime = isoToDateTime(startAttr);
      if (endAttr) {
        const durInterval = Interval.fromDateTimes(startTime, endTime);
        this._duration = durInterval.toDuration();
      } else {
        endTime = startTime.plus(this._duration);
      }
    } else {
      startTime = endTime.minus(this._duration);
    }
    const shadow = this.attachShadow({ mode: "open" });
    const wrapper = document.createElement("span");
    wrapper.classList.add("wrapper");
    const style = document.createElement("style");
    style.textContent = `
          input.duration {
            width: 8em;
          }
          label {
            margin-left: 3px;
            margin-right: 1px;
          }
        `;
    shadow.appendChild(style);
    const startLabel = wrapper.appendChild(document.createElement("label"));
    startLabel.textContent = this.startLabel;
    startLabel.classList.add("startlabel");
    const startChooser = wrapper.appendChild(new DateTimeChooser());
    this.startChooser = startChooser;
    startChooser.setAttribute("class", "start");
    const durationDiv = wrapper.appendChild(document.createElement("span"));
    durationDiv.setAttribute("class", "duration");
    const durationLabel = wrapper.appendChild(document.createElement("label"));
    durationLabel.textContent = this.durationLabel;
    durationLabel.classList.add("durationlabel");
    const durationInput = wrapper.appendChild(document.createElement("input"));
    durationInput.value = `${this.duration.toISO()}`;
    durationInput.setAttribute("class", "duration");
    const endLabel = wrapper.appendChild(document.createElement("label"));
    endLabel.textContent = this.endLabel;
    endLabel.classList.add("endlabel");
    const endChooser = wrapper.appendChild(new DateTimeChooser());
    this.endChooser = endChooser;
    endChooser.setAttribute("class", "end");
    startChooser.addEventListener("change", () => {
      this.start = startChooser.time;
    });
    durationInput.addEventListener("change", () => {
      if (!durationInput.value) {
        return;
      }
      this.duration = extractDuration(durationInput.value);
    });
    endChooser.addEventListener("change", () => {
      this.end = endChooser.time;
    });
    this.startChooser.updateTime(startTime);
    this.endChooser.updateTime(endTime);
    if (this.getAttribute(PREV_NEXT)) {
      this.createPrevNext();
    }
    shadow.appendChild(wrapper);
  }
  toInterval() {
    return Interval.fromDateTimes(this.startChooser.time, this.endChooser.time);
  }
  getTimeRange() {
    return this.toInterval();
  }
  /**
   * Updates the times without triggering the callback function.
   *
   * @param  timeRange new time interval
   */
  updateTimeRange(timeRange) {
    this.startChooser.updateTime(validStartTime(timeRange));
    this.endChooser.updateTime(validEndTime(timeRange));
    this._updateDuration(timeRange.toDuration());
  }
  get startLabel() {
    const l2 = this.getAttribute(START_LABEL);
    if (isDef(l2)) {
      return l2;
    } else {
      return DEFAULT_START_LABEL;
    }
  }
  get endLabel() {
    const l2 = this.getAttribute(END_LABEL);
    if (isDef(l2)) {
      return l2;
    } else {
      return DEFAULT_END_LABEL;
    }
  }
  get durationLabel() {
    const l2 = this.getAttribute(DUR_LABEL);
    if (isDef(l2)) {
      return l2;
    } else {
      return DEFAULT_DUR_LABEL;
    }
  }
  get start() {
    return this.startChooser.time;
  }
  set start(time3) {
    if (typeof time3 === "string") {
      time3 = DateTime.fromISO(time3);
    }
    checkLuxonValid(time3);
    this.startChooser.updateTime(time3);
    const startStr = stringify(time3.toISO());
    if (startStr !== this.getAttribute("start")) {
      this.setAttribute("start", startStr);
    }
    this.resyncValues(START_CHANGED);
  }
  get end() {
    return this.endChooser.time;
  }
  set end(time3) {
    if (typeof time3 === "string") {
      time3 = DateTime.fromISO(time3);
    }
    checkLuxonValid(time3);
    this.endChooser.updateTime(time3);
    const endStr = stringify(time3.toISO());
    if (endStr !== this.getAttribute("end")) {
      this.setAttribute("end", endStr);
    }
    this.resyncValues(END_CHANGED);
  }
  set duration(duration3) {
    this._updateDuration(duration3);
    this.resyncValues(DURATION_CHANGED);
  }
  get duration() {
    return this._duration;
  }
  _updateDuration(duration3) {
    let durationStr;
    if (typeof duration3 === "string") {
      durationStr = duration3;
      duration3 = Duration.fromISO(duration3);
    } else {
      durationStr = stringify(duration3.toISO());
    }
    checkLuxonValid(duration3);
    this._duration = duration3;
    if (durationStr !== this.getAttribute("duration")) {
      this.setAttribute("duration", durationStr);
    }
    const dur_input = this.shadowRoot?.querySelector(
      "input.duration"
    );
    if (!dur_input) {
      throw new Error("can't find input.duration in sp-timerange");
    }
    dur_input.value = durationStr;
  }
  resyncValues(curChanged) {
    if (curChanged === START_CHANGED) {
      if (this._mostRecentChanged === END_CHANGED && this.start < this.end) {
        this._updateDuration(this.toInterval().toDuration());
      } else {
        this.endChooser.updateTime(this.startChooser.time.plus(this._duration));
      }
    } else if (curChanged === DURATION_CHANGED) {
      if (this._mostRecentChanged === START_CHANGED) {
        this.endChooser.updateTime(this.startChooser.time.plus(this._duration));
      } else {
        this.startChooser.updateTime(
          this.endChooser.time.minus(this._duration)
        );
      }
    } else {
      if (this._mostRecentChanged === START_CHANGED && this.start < this.end) {
        this._updateDuration(this.toInterval().toDuration());
      } else {
        this.startChooser.updateTime(
          this.endChooser.time.minus(this._duration)
        );
      }
    }
    if (curChanged !== this._mostRecentChanged) {
      this._mostRecentChanged = curChanged;
    }
    this.dispatchEvent(new Event("change"));
    this.updateCallback(this.getTimeRange());
  }
  createPrevNext() {
    if (this.shadowRoot?.querySelector("#pastButton") != null) {
      return;
    }
    const wrapper = this.shadowRoot?.querySelector(".wrapper");
    if (wrapper == null) {
      return;
    }
    const startLabel = wrapper.querySelector("label");
    const durationInput = this.shadowRoot?.querySelector(
      "input.duration"
    );
    if (startLabel == null) {
      return;
    }
    const pastBtn = wrapper.insertBefore(
      document.createElement("button"),
      startLabel
    );
    pastBtn.setAttribute("id", "pastButton");
    pastBtn.textContent = "<";
    pastBtn.addEventListener("click", () => {
      this._mostRecentChanged = DURATION_CHANGED;
      this.startChooser.time = this.startChooser.time.minus(
        extractDuration(durationInput.value)
      );
    });
    const futureBtn = wrapper.appendChild(document.createElement("button"));
    futureBtn.setAttribute("id", "futureButton");
    futureBtn.textContent = ">";
    futureBtn.addEventListener("click", () => {
      this._mostRecentChanged = DURATION_CHANGED;
      this.endChooser.time = this.endChooser.time.plus(
        extractDuration(durationInput.value)
      );
    });
    const nowBtn = wrapper.appendChild(document.createElement("button"));
    nowBtn.setAttribute("id", "nowButton");
    nowBtn.textContent = "Now";
    nowBtn.addEventListener("click", () => {
      this._mostRecentChanged = DURATION_CHANGED;
      this.endChooser.time = DateTime.utc();
    });
  }
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === "start") {
      this.start = isoToDateTime(newValue);
    } else if (name === "end") {
      this.end = isoToDateTime(newValue);
    } else if (name === "duration") {
      this.duration = extractDuration(newValue);
    } else if (name === START_LABEL) {
      (this.shadowRoot?.querySelector(".startlabel")).textContent = newValue;
    } else if (name === END_LABEL) {
      (this.shadowRoot?.querySelector(".endlabel")).textContent = newValue;
    } else if (name === DUR_LABEL) {
      (this.shadowRoot?.querySelector(".durationLabel")).textContent = newValue;
    } else if (name === PREV_NEXT) {
      if (this.getAttribute(PREV_NEXT) === "true") {
        this.createPrevNext();
      } else {
        this.shadowRoot?.querySelector("#pastButton")?.remove();
        this.shadowRoot?.querySelector("#futureButton")?.remove();
        this.shadowRoot?.querySelector("#nowButton")?.remove();
      }
    } else {
      throw new Error(`set unknown attribute: "${name}"`);
    }
  }
  static get observedAttributes() {
    return [
      "start",
      "duration",
      "end",
      START_LABEL,
      END_LABEL,
      DUR_LABEL,
      PREV_NEXT
    ];
  }
};
customElements.define(TIMERANGE_ELEMENT, TimeRangeChooser);
function extractDuration(value) {
  let dur;
  if (value.startsWith("P")) {
    dur = Duration.fromISO(value);
  } else {
    const nDur = +Number.parseFloat(value);
    dur = Duration.fromMillis(nDur * 1e3);
  }
  return dur;
}

// src/fdsnavailability.mts
var fdsnavailability_exports = {};
__export(fdsnavailability_exports, {
  AVAILABILITY_SERVICE: () => AVAILABILITY_SERVICE,
  AvailabilityQuery: () => AvailabilityQuery,
  EARTHSCOPE_HOST: () => EARTHSCOPE_HOST,
  EMPTY_JSON: () => EMPTY_JSON,
  FORMAT_GEOCSV: () => FORMAT_GEOCSV,
  FORMAT_JSON: () => FORMAT_JSON,
  FORMAT_REQUEST: () => FORMAT_REQUEST,
  FORMAT_TEXT: () => FORMAT_TEXT,
  IRIS_HOST: () => IRIS_HOST,
  SERVICE_NAME: () => SERVICE_NAME,
  SERVICE_VERSION: () => SERVICE_VERSION,
  isValidDatasource: () => isValidDatasource,
  isValidRootType: () => isValidRootType
});
var FORMAT_JSON = "json";
var FORMAT_TEXT = "text";
var FORMAT_GEOCSV = "geocsv";
var FORMAT_REQUEST = "request";
var EMPTY_JSON = {
  version: {},
  datasources: []
};
var AVAILABILITY_SERVICE = "availability";
var SERVICE_VERSION = 1;
var SERVICE_NAME = `fdsnws-${AVAILABILITY_SERVICE}-${SERVICE_VERSION}`;
var AvailabilityQuery = class extends FDSNCommon {
  constructor(host) {
    if (!isNonEmptyStringArg(host)) {
      host = EARTHSCOPE_HOST;
    }
    super(AVAILABILITY_SERVICE, host);
  }
  /**
   * Gets/Sets the version of the fdsnws spec, 1 is currently the only value.
   *  Setting this is probably a bad idea as the code may not be compatible with
   *  the web service.
   *
   * @param value spec version, usually 1
   * @returns the query when setting, the current value when no argument
   */
  specVersion(value) {
    doStringGetterSetter(this, "specVersion", value);
    return this;
  }
  getSpecVersion() {
    return this._specVersion;
  }
  /**
   * Gets/Sets the protocol, http or https. This should match the protocol
   *  of the page loaded, but is autocalculated and generally need not be set.
   *
   * @param value protocol, usually http or https
   * @returns the query when setting, the current value when no argument
   */
  protocol(value) {
    doStringGetterSetter(this, "protocol", value);
    return this;
  }
  getProtocol() {
    return this._protocol;
  }
  /**
   * Gets/Sets the remote host to connect to.
   *
   * @param value host
   * @returns the query when setting, the current value when no argument
   */
  host(value) {
    doStringGetterSetter(this, "host", value);
    return this;
  }
  getHost() {
    return this._host;
  }
  /**
   * Gets/Sets the nodata parameter, usually 404 or 204 (default), controlling
   * the status code when no matching data is found by the service.
   *
   * @param value number for nodata, usually 404 or 204
   * @returns the query when setting, the current value when no argument
   */
  nodata(value) {
    doIntGetterSetter(this, "nodata", value);
    return this;
  }
  getNodata() {
    return this._nodata;
  }
  /**
   * Gets/Sets the port, not usually set unless not on standard http or https ports
   *
   * @param value port
   * @returns the query when setting, the current value when no argument
   */
  port(value) {
    doIntGetterSetter(this, "port", value);
    return this;
  }
  getPort() {
    return this._port;
  }
  pathBase(value) {
    doStringGetterSetter(this, "path_base", value);
    return this;
  }
  getPathBase() {
    return this._path_base;
  }
  /**
   * Gets/Sets the network code to check.
   *
   * @param value network code like IU
   * @returns the query when setting, the current value when no argument
   */
  networkCode(value) {
    doStringGetterSetter(this, "networkCode", value);
    return this;
  }
  getNetworkCode() {
    return this._networkCode;
  }
  /**
   * Gets/Sets the station code to check.
   *
   * @param value station code like ANMO
   * @returns the query when setting, the current value when no argument
   */
  stationCode(value) {
    doStringGetterSetter(this, "stationCode", value);
    return this;
  }
  getStationCode() {
    return this._stationCode;
  }
  /**
   * Gets/Sets the location code to check.
   *
   * @param value location code like 00
   * @returns the query when setting, the current value when no argument
   */
  locationCode(value) {
    doStringGetterSetter(this, "locationCode", value);
    return this;
  }
  getLocationCode() {
    return this._locationCode;
  }
  /**
   * Gets/Sets the channel code to check.
   *
   * @param value channel code like BHZ
   * @returns the query when setting, the current value when no argument
   */
  channelCode(value) {
    doStringGetterSetter(this, "channelCode", value);
    return this;
  }
  getChannelCode() {
    return this._channelCode;
  }
  /**
   * Gets/Sets the start time parameter for the query.
   *
   * @param value start time
   * @returns the query when setting, the current value when no argument
   */
  startTime(value) {
    doMomentGetterSetter(this, "startTime", value);
    return this;
  }
  getStartTime() {
    return this._startTime;
  }
  /**
   * Gets/Sets the end time parameter for the query.
   *
   * @param value end time
   * @returns the query when setting, the current value when no argument
   */
  endTime(value) {
    doMomentGetterSetter(this, "endTime", value);
    return this;
  }
  getEndTime() {
    return this._endTime;
  }
  /**
   * Sets startTime and endTime using the given time window
   *
   * @param   se time window
   * @returns    the query
   */
  timeRange(se) {
    this.startTime(validStartTime(se));
    this.endTime(validEndTime(se));
    return this;
  }
  /**
   * Gets/Sets the quality parameter for the query.
   *
   * @param value quality
   * @returns the query when setting, the current value when no argument
   */
  quality(value) {
    doStringGetterSetter(this, "quality", value);
    return this;
  }
  getQuality() {
    return this._quality;
  }
  /**
   * Gets/Sets the merge parameter for the query.
   *
   * @param value merge
   * @returns the query when setting, the current value when no argument
   */
  merge(value) {
    doStringGetterSetter(this, "merge", value);
    return this;
  }
  getMerge() {
    return this._merge;
  }
  /**
   * Gets/Sets the mergegaps parameter for the query.
   *
   * @param value merge gaps
   * @returns the query when setting, the current value when no argument
   */
  mergeGaps(value) {
    doFloatGetterSetter(this, "mergeGaps", value);
    return this;
  }
  getMergeGaps() {
    return this._mergeGaps;
  }
  /**
   * Gets/Sets the show parameter for the query.
   *
   * @param value show
   * @returns the query when setting, the current value when no argument
   */
  show(value) {
    doStringGetterSetter(this, "show", value);
    return this;
  }
  getShow() {
    return this._show;
  }
  /**
   * Gets/Sets the limit parameter for the query.
   *
   * @param value limit
   * @returns the query when setting, the current value when no argument
   */
  limit(value) {
    doIntGetterSetter(this, "limit", value);
    return this;
  }
  getLimit() {
    return this._limit;
  }
  /**
   * Gets/Sets the order by parameter for the query.
   *
   * @param value order by
   * @returns the query when setting, the current value when no argument
   */
  orderby(value) {
    doStringGetterSetter(this, "orderBy", value);
    return this;
  }
  getOrderBy() {
    return this._orderby;
  }
  /**
   * Gets/Sets the include restricted data parameter for the query.
   *
   * @param value true to include restricted data
   * @returns the query when setting, the current value when no argument
   */
  includeRestricted(value) {
    doBoolGetterSetter(this, "includerestricted", value);
    return this;
  }
  getIncludeRestricted() {
    return this._includerestricted;
  }
  /**
   * Gets/Sets the format parameter for the query. Usually not needed as is set
   * by the various query methods.
   *
   * @param value format
   * @returns the query when setting, the current value when no argument
   */
  format(value) {
    doStringGetterSetter(this, "format", value);
    return this;
  }
  getFormat() {
    return this._format;
  }
  /**
   * Get/Set the timeout in seconds for the request. Default is 30.
   *
   * @param value timeout in seconds
   * @returns the query when setting, the current value when no argument
   */
  timeout(value) {
    doFloatGetterSetter(this, "timeoutSec", value);
    return this;
  }
  getTimeout() {
    return this._timeoutSec;
  }
  /**
   * Calls query on the remote service, using configured parameters. Calls
   * queryJson internally, then unpacks the result into array of SeismogramDisplayData
   * objects.
   *
   * @returns          promise to array of SeismogramDisplayData, each representing
   * a channel-time window
   */
  query() {
    return this.queryJson().then((json2) => {
      return this.extractFromJson(json2);
    });
  }
  /**
   * Calls the query function the remote server and parses the returned data as json.
   *
   * @returns promise to the result as json
   */
  queryJson() {
    this.format(FORMAT_JSON);
    const url2 = this.formURL("query");
    const fetchInit = defaultFetchInitObj(JSON_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
        return EMPTY_JSON;
      }
      const contentType = response.headers.get("content-type");
      if (isNonEmptyStringArg(contentType) && contentType.includes(JSON_MIME)) {
        return response.json();
      }
      throw new TypeError(`Oops, we did not get JSON! ${contentType}`);
    }).then((jsonValue) => {
      if (isValidRootType(jsonValue)) {
        return jsonValue;
      }
      throw new TypeError(`Oops, we did not get valid root type json`);
    });
  }
  /**
   * Calls extent on the remote service, using configured parameters. Calls
   * extentJson internally, then unpacks the result into array of SeismogramDisplayData
   * objects.
   *
   * @returns          promise to array of SeismogramDisplayData, each representing
   * a channel-time window
   */
  extent() {
    return this.extentJson().then((json2) => {
      return this.extractFromJson(json2);
    });
  }
  /**
   * Call the extend function on the remote server and parses the returned data as json.
   *
   * @returns promise to the result as json
   */
  extentJson() {
    this.format(FORMAT_JSON);
    const url2 = this.formURL("extent");
    const fetchInit = defaultFetchInitObj(JSON_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
        return EMPTY_JSON;
      }
      const contentType = response.headers.get("content-type");
      if (isNonEmptyStringArg(contentType) && contentType.includes(JSON_MIME)) {
        return response.json();
      }
      throw new TypeError(`Oops, we did not get JSON! ${contentType}`);
    }).then((jsonValue) => {
      if (isValidRootType(jsonValue)) {
        return jsonValue;
      }
      throw new TypeError(`Oops, we did not get valid root type json`);
    });
  }
  /**
   * Calls query on the remote service using POST, using configured parameters
   * and forms the POST body using the channelTimeList. Calls
   * postQueryJson internally, then unpacks the result into array of SeismogramDisplayData
   * objects.
   *
   * @param channelTimeList array of channel-time windows for the request
   * @returns          promise to array of SeismogramDisplayData, each representing
   * a channel-time window
   */
  postQuery(channelTimeList) {
    return this.postQueryJson(channelTimeList).then((json2) => {
      return this.extractFromJson(json2);
    });
  }
  postExtent(channelTimeList) {
    return this.postExtentJson(channelTimeList).then((json2) => {
      return this.extractFromJson(json2);
    });
  }
  postExtentJson(channelTimeList) {
    return this.postJson(channelTimeList, "extent");
  }
  postQueryJson(channelTimeList) {
    return this.postJson(channelTimeList, "query");
  }
  postJson(channelTimeList, method) {
    this.format(FORMAT_JSON);
    return this.postRaw(channelTimeList, method).then((response) => {
      if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
        return EMPTY_JSON;
      }
      const contentType = response.headers.get("content-type");
      if (isNonEmptyStringArg(contentType) && contentType.includes(JSON_MIME)) {
        return response.json();
      }
      throw new TypeError(`Oops, we did not get JSON! ${contentType}`);
    }).then((jsonValue) => {
      if (isValidRootType(jsonValue)) {
        return jsonValue;
      }
      throw new TypeError(`Oops, we did not get valid root type json`);
    });
  }
  postRaw(channelTimeList, method) {
    if (channelTimeList.length === 0) {
      return Promise.resolve(
        new Response(null, {
          status: 204
        })
      );
    } else {
      const fetchInit = defaultFetchInitObj(JSON_MIME);
      fetchInit.method = "POST";
      fetchInit.body = this.createPostBody(channelTimeList);
      return fetch(appendToPath(this.formBaseURL(), `${method}?`), fetchInit).then(
        function(response) {
          if (response.ok) {
            return response;
          }
          throw new Error("Fetch response was not ok.");
        }
      );
    }
  }
  extractFromJson(jsonChanTimes) {
    const out = [];
    const knownNets = /* @__PURE__ */ new Map();
    if (isDef(jsonChanTimes.datasources)) {
      for (const ds of jsonChanTimes.datasources) {
        if (isValidDatasource(ds)) {
          let n2 = knownNets.get(ds.network);
          if (!n2) {
            n2 = new Network(ds.network);
            knownNets.set(ds.network, n2);
          }
          let s2 = null;
          for (const ss of n2.stations) {
            if (ss.stationCode === ds.station) {
              s2 = ss;
            }
          }
          if (!s2) {
            s2 = new Station(n2, ds.station);
            n2.stations.push(s2);
          }
          const c = new Channel(s2, ds.channel, ds.location);
          if (isNonEmptyStringArg(ds.earliest) && isNonEmptyStringArg(ds.latest)) {
            out.push(
              SeismogramDisplayData.fromChannelAndTimes(
                c,
                isoToDateTime(ds.earliest),
                isoToDateTime(ds.latest)
              )
            );
          } else if (ds.timespans) {
            for (const ts of ds.timespans) {
              if (Array.isArray(ts) && ts.length === 2 && typeof ts[0] === "string" && typeof ts[1] === "string") {
                out.push(
                  SeismogramDisplayData.fromChannelAndTimes(
                    c,
                    isoToDateTime(ts[0]),
                    isoToDateTime(ts[1])
                  )
                );
              } else {
                throw new TypeError("invalid timespans: " + stringify(ts));
              }
            }
          }
        }
      }
    }
    return out;
  }
  createPostBody(channelTimeList) {
    let out = "";
    if (this._quality) {
      out += this.makePostParm("quality", this.quality());
    }
    if (this._merge) {
      out += this.makePostParm("merge", this.merge());
    }
    if (isNumArg(this._mergeGaps) && (this._format === "query" || this._format === "queryauth")) {
      out += this.makePostParm("mergegaps", this.mergeGaps());
    }
    if (this._show && (this._format === "query" || this._format === "queryauth")) {
      out += this.makePostParm("show", this.show());
    }
    if (isNumArg(this._limit) && this._limit > 0) {
      out += this.makePostParm("limit", this.limit());
    }
    if (this._orderby) {
      out += this.makePostParm("orderby", this.orderby());
    }
    if (this._includerestricted) {
      out += this.makePostParm("includerestricted", this.includeRestricted());
    }
    if (this._format) {
      out += this.makePostParm("format", this.format());
    }
    if (this._nodata) {
      out += this.makePostParm("nodata", this.nodata());
    }
    for (const ct of channelTimeList) {
      if (isDef(ct.channel)) {
        const sta = ct.channel.station;
        const net = sta.network;
        out += `${net.networkCode} ${sta.stationCode} ${ct.channel.locationCode} ${ct.channel.channelCode} ${toIsoWoZ(ct.startTime)} ${toIsoWoZ(ct.endTime)}`;
        out += "\n";
      } else {
        throw new Error("Channel in missing in createPostBody");
      }
    }
    return out;
  }
  /**
   * Forms the base of the url for accessing the dataselect service.
   *
   * @returns         URL as string
   */
  formBaseURL() {
    let colon = ":";
    const protocol = protocolForKnownHost(this._host, this._protocol);
    if (protocol.endsWith(colon)) {
      colon = "";
    }
    const port = this.defaultPortStringForProtocol(protocol);
    const path2 = `${this._path_base}/${this._service}/${this._specVersion}`;
    return `${protocol}${colon}//${this._host}${port}/${path2}`;
  }
  formVersionURL() {
    return appendToPath(this.formBaseURL(), "version");
  }
  /**
   * Queries the remote web service to get its version
   *
   * @returns Promise to version string
   */
  queryVersion() {
    const url2 = this.formVersionURL();
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then(
      (response) => {
        if (response.status === 200) {
          return response.text();
        } else {
          throw new Error(`Status not 200: ${response.status}`);
        }
      }
    );
  }
  makePostParm(name, val) {
    return name + "=" + stringify(val) + "\n";
  }
  formURL(method) {
    if (hasNoArgs(method)) {
      method = "query";
    }
    let url2 = appendToPath(this.formBaseURL(), `/${method}?`);
    if (this._networkCode) {
      url2 = url2 + makeParam("net", this._networkCode);
    }
    if (this._stationCode) {
      url2 = url2 + makeParam("sta", this._stationCode);
    }
    if (this._locationCode) {
      url2 = url2 + makeParam("loc", this._locationCode);
    }
    if (this._channelCode) {
      url2 = url2 + makeParam("cha", this._channelCode);
    }
    if (this._startTime) {
      url2 = url2 + makeParam("starttime", toIsoWoZ(this._startTime));
    }
    if (this._endTime) {
      url2 = url2 + makeParam("endtime", toIsoWoZ(this._endTime));
    }
    if (this._quality) {
      url2 = url2 + makeParam("quality", this._quality);
    }
    if (this._merge) {
      url2 = url2 + makeParam("merge", this._merge);
    }
    if (this._mergeGaps) {
      url2 = url2 + makeParam("mergegaps", this._mergeGaps);
    }
    if (this._show) {
      url2 = url2 + makeParam("show", this._show);
    }
    if (isNumArg(this._limit) && this._limit > 0) {
      url2 = url2 + makeParam("limit", this._limit);
    }
    if (this._orderby) {
      url2 = url2 + makeParam("orderby", this._orderby);
    }
    if (this._includerestricted) {
      url2 = url2 + makeParam("includerestricted", this._includerestricted);
    }
    if (this._format) {
      url2 = url2 + makeParam("format", this._format);
    }
    if (this._nodata) {
      url2 = url2 + makeParam("nodata", this._nodata);
    }
    if (url2.endsWith("&") || url2.endsWith("?")) {
      url2 = url2.substr(0, url2.length - 1);
    }
    return url2;
  }
};
function isValidRootType(jsonValue) {
  if (!jsonValue || typeof jsonValue !== "object") {
    throw new TypeError("json is not object");
  }
  const jsonObj = jsonValue;
  if (Array.isArray(jsonObj.datasources) && jsonObj.datasources.every(isValidDatasource) && typeof jsonObj.version === "number") {
    return true;
  } else {
    throw new TypeError("json is not valid for FDSN Availability");
  }
}
function isValidDatasource(jsonValue) {
  if (!jsonValue || typeof jsonValue !== "object") {
    throw new TypeError("json is not object");
  }
  const jsonObj = jsonValue;
  if (typeof jsonObj.network === "string" && typeof jsonObj.station === "string" && typeof jsonObj.location === "string" && typeof jsonObj.channel === "string") {
    return true;
  } else {
    throw new TypeError("json datasource is not valid for FDSN Availability");
  }
}

// src/fdsndatacenters.mts
var fdsndatacenters_exports = {};
__export(fdsndatacenters_exports, {
  DATACENTERS_PATH_BASE: () => DATACENTERS_PATH_BASE,
  DATACENTERS_SERVICE: () => DATACENTERS_SERVICE,
  DataCentersQuery: () => DataCentersQuery,
  isValidRootType: () => isValidRootType2
});

// src/fdsndataselect.mts
var fdsndataselect_exports = {};
__export(fdsndataselect_exports, {
  DATASELECT_SERVICE: () => DATASELECT_SERVICE,
  DataSelectQuery: () => DataSelectQuery,
  EARTHSCOPE_HOST: () => EARTHSCOPE_HOST,
  FORMAT_MINISEED: () => FORMAT_MINISEED,
  FORMAT_MINISEED_THREE: () => FORMAT_MINISEED_THREE,
  IRIS_HOST: () => IRIS_HOST,
  SERVICE_NAME: () => SERVICE_NAME2,
  SERVICE_VERSION: () => SERVICE_VERSION2,
  createDataSelectQuery: () => createDataSelectQuery
});
var FORMAT_MINISEED = "miniseed";
var FORMAT_MINISEED_THREE = "miniseed3";
var DATASELECT_SERVICE = "dataselect";
var SERVICE_VERSION2 = 1;
var SERVICE_NAME2 = `fdsnws-${DATASELECT_SERVICE}-${SERVICE_VERSION2}`;
var DataSelectQuery = class _DataSelectQuery extends FDSNCommon {
  constructor(host) {
    if (!isNonEmptyStringArg(host)) {
      host = EARTHSCOPE_HOST;
    }
    super(DATASELECT_SERVICE, host);
    if (host === EARTHSCOPE_HOST) {
      this.protocol("https:");
    }
  }
  /**
   * Gets/Sets the version of the fdsnws spec, 1 is currently the only value.
   *  Setting this is probably a bad idea as the code may not be compatible with
   *  the web service.
   *
   * @param value spec version, usually 1
   * @returns new value if getting, this if setting
   */
  specVersion(value) {
    doStringGetterSetter(this, "specVersion", value);
    return this;
  }
  getSpecVersion() {
    return this._specVersion;
  }
  /**
   * Gets/Sets the protocol, http or https. This should match the protocol
   *  of the page loaded, but is autocalculated and generally need not be set.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  protocol(value) {
    doStringGetterSetter(this, "protocol", value);
    return this;
  }
  getProtocol() {
    return this._protocol;
  }
  /**
   * Gets/Sets the remote host to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  host(value) {
    doStringGetterSetter(this, "host", value);
    return this;
  }
  getHost() {
    return this._host;
  }
  /**
   * Gets/Sets the nodata parameter, usually 404 or 204 (default), controlling
   * the status code when no matching data is found by the service.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  nodata(value) {
    doIntGetterSetter(this, "nodata", value);
    return this;
  }
  getNodata() {
    return this._nodata;
  }
  /**
   * Gets/Sets the remote port to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  port(value) {
    doIntGetterSetter(this, "port", value);
    return this;
  }
  getPort() {
    return this._port;
  }
  pathBase(value) {
    doStringGetterSetter(this, "path_base", value);
    return this;
  }
  getPathBase() {
    return this._path_base;
  }
  /**
   * Get/Set the network query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  networkCode(value) {
    doStringGetterSetter(this, "networkCode", value);
    return this;
  }
  getNetworkCode() {
    return this._networkCode;
  }
  /**
   * Get/Set the station query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  stationCode(value) {
    doStringGetterSetter(this, "stationCode", value);
    return this;
  }
  getStationCode() {
    return this._stationCode;
  }
  /**
   * Get/Set the location code query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  locationCode(value) {
    doStringGetterSetter(this, "locationCode", value);
    return this;
  }
  getLocationCode() {
    return this._locationCode;
  }
  /**
   * Get/Set the channel query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  channelCode(value) {
    doStringGetterSetter(this, "channelCode", value);
    return this;
  }
  getChannelCode() {
    return this._channelCode;
  }
  nslcCodes(channelId) {
    this.networkCode(channelId.networkCode);
    this.stationCode(channelId.stationCode);
    this.locationCode(channelId.locationCode);
    this.channelCode(channelId.channelCode);
    return this;
  }
  /**
   * Get/Set the starttime query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  startTime(value) {
    doMomentGetterSetter(this, "startTime", value);
    return this;
  }
  getStartTime() {
    return this._startTime;
  }
  /**
   * Get/Set the endtime query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  endTime(value) {
    doMomentGetterSetter(this, "endTime", value);
    return this;
  }
  getEndTime() {
    return this._endTime;
  }
  /**
   * Sets startTime and endTime using the given time range
   *
   * @param   se time range
   * @returns     this
   */
  timeRange(se) {
    this.startTime(validStartTime(se));
    this.endTime(validEndTime(se));
    return this;
  }
  /**
   * Get/Set the quality query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  quality(value) {
    doStringGetterSetter(this, "quality", value);
    return this;
  }
  getQuality() {
    return this._quality;
  }
  /**
   * Get/Set the minimum length query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minimumLength(value) {
    doFloatGetterSetter(this, "minimumLength", value);
    return this;
  }
  getMinimumLength() {
    return this._minimumLength;
  }
  /**
   * Get/Set the longest only query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  longestOnly(value) {
    doBoolGetterSetter(this, "longestOnly", value);
    return this;
  }
  getLongestOnly() {
    return this._longestOnly;
  }
  /**
   * set or get the repository paramter. This is an IRIS-specific
   * parameter that will not work with other dataselect web services.
   *
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  repository(value) {
    doStringGetterSetter(this, "repository", value);
    return this;
  }
  getRepository() {
    return this._repository;
  }
  /**
   * Get/Set the format query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  format(value) {
    doStringGetterSetter(this, "format", value);
    return this;
  }
  getFormat() {
    return this._format;
  }
  /**
   * Get/Set the timeout in seconds for the request. Default is 30.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  timeout(value) {
    doFloatGetterSetter(this, "timeoutSec", value);
    return this;
  }
  getTimeout() {
    return this._timeoutSec;
  }
  /**
   * queries the web service using the configured parameters, parsing the response
   * into miniseed data records.
   *
   * @returns Promise to Array of miniseed.DataRecords
   */
  queryDataRecords() {
    this.format(FORMAT_MINISEED);
    const url2 = this.formURL();
    const fetchInit = defaultFetchInitObj(MINISEED_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 204 || isDef(this._nodata) && response.status === this.getNodata()) {
        return new ArrayBuffer(0);
      } else {
        return response.arrayBuffer();
      }
    }).then(function(rawBuffer) {
      const dataRecords = parseDataRecords(rawBuffer);
      return dataRecords;
    });
  }
  /**
   * queries the web service using the configured parameters, parsing the response
   * into miniseed3 data records.
   *
   * @returns Promise to Array of mseed3.MSeed3Record
   */
  queryMS3Records() {
    this.format(FORMAT_MINISEED_THREE);
    const url2 = this.formURL();
    const fetchInit = defaultFetchInitObj(MINISEED_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 204 || isDef(this._nodata) && response.status === this.getNodata()) {
        return new ArrayBuffer(0);
      } else {
        return response.arrayBuffer();
      }
    }).then(function(rawBuffer) {
      const dataRecords = parseMSeed3Records(rawBuffer);
      return dataRecords;
    });
  }
  /**
   * queries the web service using the configured parameters, parsing the response
   * into miniseed data records and then combining the data records into
   * Seismogram objects.
   *
   * @returns Promise to Array of Seismogram objects
   */
  querySeismograms() {
    if (this._format === FORMAT_MINISEED_THREE) {
      return this.queryMS3Records().then((dataRecords) => {
        return seismogramPerChannel2(dataRecords);
      });
    } else {
      return this.queryDataRecords().then((dataRecords) => {
        return seismogramPerChannel(dataRecords);
      });
    }
  }
  postQueryDataRecords(channelTimeList) {
    return this.postQueryRaw(channelTimeList).then((fetchResponse) => {
      if (fetchResponse.ok) {
        return fetchResponse.arrayBuffer().then((ab) => {
          return parseDataRecords(ab);
        });
      } else {
        log("fetchResponse not ok");
        return [];
      }
    });
  }
  postQueryMS3Records(channelTimeList) {
    return this.postQueryRaw(channelTimeList).then((fetchResponse) => {
      if (fetchResponse.ok) {
        return fetchResponse.arrayBuffer().then((ab) => {
          return parseMSeed3Records(ab);
        });
      } else {
        log("fetchResponse not ok");
        return [];
      }
    });
  }
  /**
   * query the dataselect server using post, which allows for multiple
   * channel-timeranges at once. This assumes that there are not multiple
   * time ranges for the same channel as the results, encapsulated as
   * SeismogramDisplayData objects, are returned one seismogram
   * per channel, which may contain gaps. The original channel and timerange are
   * also populated with each result.
   *
   * @param   sddList array of SeismogramDisplayData objects
   * that will be filled in with the resulting seismogram
   * @returns Promise to the input Array of SeismogramDisplayData objects, each with the
   * seismogram containing the data returned from the server
   */
  postQuerySeismograms(sddList) {
    let seismogramPromise;
    if (this._format === FORMAT_MINISEED_THREE) {
      seismogramPromise = this.postQueryMS3Records(sddList).then(
        (dataRecords) => {
          return seismogramSegmentPerChannel2(dataRecords);
        }
      );
    } else {
      seismogramPromise = this.postQueryDataRecords(sddList).then(
        (dataRecords) => {
          return seismogramSegmentPerChannel(dataRecords);
        }
      );
    }
    return seismogramPromise.then((seisArray) => {
      for (const sdd of sddList) {
        const sddNslc = sdd.nslcId;
        const segList = seisArray.filter(
          (s2) => s2.nslcId.equals(sddNslc) && s2.timeRange.overlaps(sdd.timeRange)
        );
        if (segList.length > 0) {
          const seis = new Seismogram(segList).trim(sdd.timeRange);
          sdd.seismogram = seis;
        }
      }
      return sddList;
    });
  }
  postQueryRaw(sddList) {
    if (sddList.length === 0) {
      return Promise.resolve(
        new Response(null, {
          status: 204
        })
      );
    } else {
      return this.postQueryRawWithBody(_DataSelectQuery.createPostBody(sddList));
    }
  }
  postQueryRawWithBody(body) {
    const fetchInit = defaultFetchInitObj(MINISEED_MIME);
    fetchInit.method = "POST";
    fetchInit.body = body;
    return doFetchWithTimeout(
      this.formPostURL(),
      fetchInit,
      this._timeoutSec * 1e3
    );
  }
  static createPostBody(sddList) {
    let out = "";
    for (const sdd of sddList) {
      const locCode = sdd.locationCode.trim() === "" ? "--" : sdd.locationCode;
      out += `${sdd.networkCode} ${sdd.stationCode} ${locCode} ${sdd.channelCode} ${toIsoWoZ(sdd.startTime)} ${toIsoWoZ(sdd.endTime)}`;
      out += "\n";
    }
    return out;
  }
  /**
   * Forms the base of the url for accessing the dataselect service.
   *
   * @returns         URL as string
   */
  formBaseURL() {
    let colon = ":";
    const protocol = protocolForKnownHost(this._host, this._protocol);
    if (protocol.endsWith(colon)) {
      colon = "";
    }
    const port = this.defaultPortStringForProtocol(protocol);
    const path2 = `${this._path_base}/${this._service}/${this._specVersion}`;
    return `${protocol}${colon}//${this._host}${port}/${path2}`;
  }
  formVersionURL() {
    return appendToPath(this.formBaseURL(), "version");
  }
  /**
   * Queries the remote web service to get its version
   *
   * @returns Promise to version string
   */
  queryVersion() {
    const url2 = this.formVersionURL();
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then(
      (response) => {
        if (response.status === 200) {
          return response.text();
        } else {
          throw new Error(`Status not 200: ${response.status}`);
        }
      }
    );
  }
  formPostURL() {
    return appendToPath(this.formBaseURL(), "query");
  }
  formURL() {
    let url2 = appendToPath(this.formBaseURL(), "query?");
    if (isStringArg(this._networkCode) && this._networkCode.length > 0 && this._networkCode !== "*") {
      url2 = url2 + makeParam("net", this._networkCode);
    }
    if (isStringArg(this._stationCode) && this._stationCode.length > 0 && this._stationCode !== "*") {
      url2 = url2 + makeParam("sta", this._stationCode);
    }
    if (isStringArg(this._locationCode) && this._locationCode.length > 0 && this._locationCode !== "*") {
      url2 = url2 + makeParam("loc", this._locationCode);
    }
    if (isStringArg(this._channelCode) && this._channelCode.length > 0 && this._channelCode !== "*") {
      url2 = url2 + makeParam("cha", this._channelCode);
    }
    if (this._startTime) {
      url2 = url2 + makeParam("starttime", toIsoWoZ(this._startTime));
    }
    if (this._endTime) {
      url2 = url2 + makeParam("endtime", toIsoWoZ(this._endTime));
    }
    if (this._quality) {
      url2 = url2 + makeParam("quality", this._quality);
    }
    if (this._minimumLength) {
      url2 = url2 + makeParam("minimumlength", this._minimumLength);
    }
    if (this._repository) {
      url2 = url2 + makeParam("repository", this._repository);
    }
    if (this._longestOnly) {
      url2 = url2 + makeParam("longestonly", this._longestOnly);
    }
    if (this._format) {
      url2 = url2 + makeParam("format", this._format);
    }
    if (this._nodata) {
      url2 = url2 + makeParam("nodata", this._nodata);
    }
    if (url2.endsWith("&") || url2.endsWith("?")) {
      url2 = url2.substr(0, url2.length - 1);
    }
    return url2;
  }
};
function createDataSelectQuery(params) {
  if (!params || typeof params !== "object") {
    throw new Error("params null or not an object");
  }
  const out = new DataSelectQuery();
  if (params.net) {
    out.networkCode(params.net);
  }
  if (params.network) {
    out.networkCode(params.network);
  }
  if (params.networkCode) {
    out.networkCode(params.networkCode);
  }
  if (params.sta) {
    out.stationCode(params.sta);
  }
  if (params.station) {
    out.stationCode(params.station);
  }
  if (params.stationCode) {
    out.stationCode(params.stationCode);
  }
  if (params.loc) {
    out.locationCode(params.loc);
  }
  if (params.location) {
    out.locationCode(params.location);
  }
  if (params.locationCode) {
    out.locationCode(params.locationCode);
  }
  if (params.chan) {
    out.channelCode(params.chan);
  }
  if (params.channel) {
    out.channelCode(params.channel);
  }
  if (params.channelCode) {
    out.channelCode(params.channelCode);
  }
  if (params.start || params.starttime) {
    const s2 = params.start ? params.start : params.starttime;
    out.startTime(isoToDateTime(s2));
  }
  if (params.end || params.endtime) {
    const e = params.end ? params.end : params.endtime;
    out.endTime(isoToDateTime(e));
  }
  if (params.quality) {
    out.quality(params.quality);
  }
  if (params.minimumlength) {
    out.minimumLength(parseInt(params.minimumlength));
  }
  if (params.repository) {
    out.repository(params.repository);
  }
  if (params.longestonly) {
    out.longestOnly(params.longestonly.toLowerCase() === "true");
  }
  if (params.format) {
    out.format(params.format);
  }
  if (params.nodata) {
    out.nodata(parseInt(params.nodata));
  }
  if (params.host) {
    out.host(params.host);
  }
  if (params.port) {
    out.port(parseInt(params.port));
  }
  if (params.specVersion) {
    out.specVersion(params.specVersion);
  }
  return out;
}

// src/fdsnevent.mts
var fdsnevent_exports = {};
__export(fdsnevent_exports, {
  EVENT_SERVICE: () => EVENT_SERVICE,
  EventQuery: () => EventQuery,
  SERVICE_NAME: () => SERVICE_NAME3,
  SERVICE_VERSION: () => SERVICE_VERSION3,
  USGS_HOST: () => USGS_HOST
});
var EVENT_SERVICE = "event";
var SERVICE_VERSION3 = 1;
var SERVICE_NAME3 = `fdsnws-event-${SERVICE_VERSION3}`;
var EventQuery = class extends FDSNCommon {
  constructor(host) {
    if (!isNonEmptyStringArg(host)) {
      host = USGS_HOST;
    }
    super(EVENT_SERVICE, host);
  }
  /**
   * Gets/Sets the version of the fdsnws spec, 1 is currently the only value.
   *  Setting this is probably a bad idea as the code may not be compatible with
   *  the web service.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  specVersion(value) {
    doStringGetterSetter(this, "specVersion", value);
    return this;
  }
  getSpecVersion() {
    return this._specVersion;
  }
  /**
   * Gets/Sets the protocol, http or https. This should match the protocol
   *  of the page loaded, but is autocalculated and generally need not be set.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  protocol(value) {
    doStringGetterSetter(this, "protocol", value);
    return this;
  }
  getProtocol() {
    return this._protocol;
  }
  /**
   * Gets/Sets the remote host to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  host(value) {
    doStringGetterSetter(this, "host", value);
    return this;
  }
  getHost() {
    return this._host;
  }
  /**
   * Gets/Sets the remote port to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  port(value) {
    doIntGetterSetter(this, "port", value);
    return this;
  }
  getPort() {
    return this._port;
  }
  pathBase(value) {
    doStringGetterSetter(this, "path_base", value);
    return this;
  }
  getPathBase() {
    return this._path_base;
  }
  /**
   * Gets/Sets the nodata parameter, usually 404 or 204 (default), controlling
   * the status code when no matching data is found by the service.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  nodata(value) {
    doIntGetterSetter(this, "nodata", value);
    return this;
  }
  getNodata() {
    return this._nodata;
  }
  /**
   * Get/Set the timeout in seconds for the request. Default is 30.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  timeout(value) {
    doFloatGetterSetter(this, "timeoutSec", value);
    return this;
  }
  getTimeout() {
    return this._timeoutSec;
  }
  /**
   * Get/Set the eventid query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  eventId(value) {
    doStringGetterSetter(this, "eventId", value);
    return this;
  }
  getEventId() {
    return this._eventId;
  }
  /**
   * Get/Set the starttime query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  startTime(value) {
    doMomentGetterSetter(this, "startTime", value);
    return this;
  }
  getStartTime() {
    return this._startTime;
  }
  /**
   * Get/Set the endtime query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  endTime(value) {
    doMomentGetterSetter(this, "endTime", value);
    return this;
  }
  getEndTime() {
    return this._endTime;
  }
  /**
   * Sets startTime and endTime using the given time window
   *
   * @param   se time window
   * @returns     this
   */
  timeRange(se) {
    this.startTime(validStartTime(se));
    this.endTime(validEndTime(se));
    return this;
  }
  /**
   * Get/Set the updatedafter query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  updatedAfter(value) {
    doMomentGetterSetter(this, "updatedAfter", value);
    return this;
  }
  getUpdatedAfter() {
    return this._updatedAfter;
  }
  /**
   * Get/Set the minmag query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minMag(value) {
    doFloatGetterSetter(this, "minMag", value);
    return this;
  }
  getMinMag() {
    return this._minMag;
  }
  /**
   * Get/Set the maxmag query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  maxMag(value) {
    doFloatGetterSetter(this, "maxMag", value);
    return this;
  }
  getMaxMag() {
    return this._maxMag;
  }
  /**
   * Get/Set the magnitudetype query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  magnitudeType(value) {
    doStringGetterSetter(this, "magnitudeType", value);
    return this;
  }
  getMagnitudeType() {
    return this._magnitudeType;
  }
  /**
   * Get/Set the mindepth query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minDepth(value) {
    doFloatGetterSetter(this, "minDepth", value);
    return this;
  }
  getMinDepth() {
    return this._minDepth;
  }
  /**
   * Get/Set the maxdepth query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  maxDepth(value) {
    doFloatGetterSetter(this, "maxDepth", value);
    return this;
  }
  getMaxDepth() {
    return this._maxDepth;
  }
  /**
   * Get/Set the minlat query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minLat(value) {
    doFloatGetterSetter(this, "minLat", value);
    return this;
  }
  getMinLat() {
    return this._minLat;
  }
  /**
   * Get/Set the maxlat query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  maxLat(value) {
    doFloatGetterSetter(this, "maxLat", value);
    return this;
  }
  getMaxLat() {
    return this._maxLat;
  }
  /**
   * Get/Set the minlon query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minLon(value) {
    doFloatGetterSetter(this, "minLon", value);
    return this;
  }
  getMinLon() {
    return this._minLon;
  }
  /**
   * Get/Set the maxlon query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  maxLon(value) {
    doFloatGetterSetter(this, "maxLon", value);
    return this;
  }
  getMaxLon() {
    return this._maxLon;
  }
  /**
   * Get/Set the latitude query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  latitude(value) {
    doFloatGetterSetter(this, "latitude", value);
    return this;
  }
  getLatitude() {
    return this._latitude;
  }
  /**
   * Get/Set the longitude query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  longitude(value) {
    doFloatGetterSetter(this, "longitude", value);
    return this;
  }
  getLongitude() {
    return this._longitude;
  }
  /**
   * Get/Set the minradius query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minRadius(value) {
    doFloatGetterSetter(this, "minRadius", value);
    return this;
  }
  getMinRadius() {
    return this._minRadius;
  }
  /**
   * Get/Set the maxradius query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  maxRadius(value) {
    doFloatGetterSetter(this, "maxRadius", value);
    return this;
  }
  getMaxRadius() {
    return this._maxRadius;
  }
  /**
   * Get/Set the includearrivals query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  includeArrivals(value) {
    doBoolGetterSetter(this, "includeArrivals", value);
    return this;
  }
  getIncludeArrivals() {
    return this._includeArrivals;
  }
  /**
   * Get/Set the includeallorigins query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  includeAllOrigins(value) {
    doBoolGetterSetter(this, "includeAllOrigins", value);
    return this;
  }
  getIncludeAllOrigins() {
    return this._includeAllOrigins;
  }
  /**
   * Get/Set the includeallmagnitudes query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  includeAllMagnitudes(value) {
    doBoolGetterSetter(this, "includeAllMagnitudes", value);
    return this;
  }
  getIncludeAllMagnitudes() {
    return this._includeAllMagnitudes;
  }
  /**
   * Get/Set the format query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  format(value) {
    doStringGetterSetter(this, "format", value);
    return this;
  }
  getFormat() {
    return this._format;
  }
  /**
   * Get/Set the limit query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  limit(value) {
    doIntGetterSetter(this, "limit", value);
    return this;
  }
  getLimit() {
    return this._limit;
  }
  /**
   * Get/Set the offset query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  offset(value) {
    doIntGetterSetter(this, "offset", value);
    return this;
  }
  getOffset() {
    return this._offset;
  }
  /**
   * Get/Set the orderby query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  orderBy(value) {
    doStringGetterSetter(this, "orderBy", value);
    return this;
  }
  getOrderBy() {
    return this._orderBy;
  }
  /**
   * Get/Set the catalog query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  catalog(value) {
    doStringGetterSetter(this, "catalog", value);
    return this;
  }
  getCatalog() {
    return this._catalog;
  }
  /**
   * Get/Set the contributor query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  contributor(value) {
    doStringGetterSetter(this, "contributor", value);
    return this;
  }
  getContributor() {
    return this._contributor;
  }
  latLonRegion(value) {
    if (value instanceof LatLonBox) {
      this._minLat = value.south;
      this._maxLat = value.north;
      this._minLon = value.west;
      this._maxLon = value.east;
      this._latitude = void 0;
      this._longitude = void 0;
      this._minRadius = void 0;
      this._maxRadius = void 0;
    } else if (value instanceof LatLonRadius) {
      this._latitude = value.latitude;
      this._longitude = value.longitude;
      this._minRadius = value.minRadius;
      this._maxRadius = value.maxRadius;
      this._minLat = void 0;
      this._maxLat = void 0;
      this._minLon = void 0;
      this._maxLon = void 0;
    } else if (!isDef(value)) {
      this._latitude = void 0;
      this._longitude = void 0;
      this._minRadius = void 0;
      this._maxRadius = void 0;
      this._minLat = void 0;
      this._maxLat = void 0;
      this._minLon = void 0;
      this._maxLon = void 0;
    } else {
      throw new Error(
        `value argument is optional or LatLonRegion, but was type ${typeof value}, '${stringify(value)}' `
      );
    }
    return this;
  }
  /**
   * Checks to see if any parameter that would limit the data
   * returned is set. This is a crude, coarse check to make sure
   * the client doesn't ask for EVERYTHING the server has.
   *
   * @returns true is some parameter is set
   */
  isSomeParameterSet() {
    return isDef(this._eventId) || isDef(this._startTime) || isDef(this._endTime) || isDef(this._minLat) || isDef(this._maxLat) || isDef(this._minLon) || isDef(this._maxLon) || isDef(this._latitude) || isDef(this._longitude) || isDef(this._minRadius) || isDef(this._maxRadius) || isDef(this._minDepth) || isDef(this._maxDepth) || isDef(this._limit) || isDef(this._minMag) || isDef(this._maxMag) || isDef(this._updatedAfter) || isDef(this._catalog) || isDef(this._contributor);
  }
  /**
   * Queries the remote service and parses the returned xml.
   *
   *  @returns Promise to an Array of Quake objects.
   */
  query() {
    return this.queryEventParameters().then((eventParameters) => {
      return eventParameters.eventList;
    });
  }
  queryEventParameters() {
    return this.queryRawXml().then((rawXml) => {
      return parseQuakeML(rawXml, this._host);
    });
  }
  /**
   * Queries the remote server, to get QuakeML xml.
   *
   * @returns xml Document
   */
  queryRawXml() {
    if (!this.isSomeParameterSet()) {
      throw new Error(
        "Must set some parameter to avoid asking for everything."
      );
    }
    const url2 = this.formURL();
    const fetchInit = defaultFetchInitObj(XML_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 200) {
        return response.text();
      } else if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
        return FAKE_EMPTY_XML2;
      } else {
        throw new Error(`Status not successful: ${response.status}`);
      }
    }).then(function(rawXmlText) {
      return new DOMParser().parseFromString(rawXmlText, XML_MIME);
    });
  }
  /**
   * Forms the basic URL to contact the web service, without any query paramters
   *
   * @returns the url
   */
  formBaseURL() {
    let colon = ":";
    if (!this._host || this._host === USGS_HOST) {
      this._host = USGS_HOST;
      this._protocol = "https:";
    }
    const protocol = protocolForKnownHost(this._host, this._protocol);
    if (protocol.endsWith(colon)) {
      colon = "";
    }
    const port = this.defaultPortStringForProtocol(protocol);
    const path2 = `${this._path_base}/${this._service}/${this._specVersion}`;
    return `${protocol}${colon}//${this._host}${port}/${path2}`;
  }
  /**
   * Forms the URL to get catalogs from the web service, without any query paramters
   *
   * @returns the url
   */
  formCatalogsURL() {
    return appendToPath(this.formBaseURL(), "catalogs");
  }
  /**
   * Queries the remote web service to get known catalogs
   *
   * @returns Promise to Array of catalog names
   */
  queryCatalogs() {
    const url2 = this.formCatalogsURL();
    const fetchInit = defaultFetchInitObj(XML_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 200) {
        return response.text();
      } else {
        throw new Error(`Status not 200: ${response.status}`);
      }
    }).then((rawXmlText) => {
      return new DOMParser().parseFromString(rawXmlText, XML_MIME);
    }).then((rawXml) => {
      if (!rawXml) {
        throw new Error("raw xml from DOMParser is null.");
      }
      const top2 = rawXml.documentElement;
      if (!top2) {
        throw new Error("documentElement in xml from DOMParser is null.");
      }
      const catalogArray = top2.getElementsByTagName("Catalog");
      const out = [];
      if (catalogArray) {
        for (let i = 0; i < catalogArray.length; i++) {
          const item = catalogArray.item(i);
          if (item && isDef(item.textContent)) {
            out.push(item.textContent);
          }
        }
      }
      return out;
    });
  }
  /**
   * Forms the URL to get contributors from the web service, without any query paramters
   *
   * @returns the url
   */
  formContributorsURL() {
    return appendToPath(this.formBaseURL(), "contributors");
  }
  /**
   * Queries the remote web service to get known contributors
   *
   * @returns Promise to Array of contributor names
   */
  queryContributors() {
    const url2 = this.formContributorsURL();
    const fetchInit = defaultFetchInitObj(XML_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 200) {
        return response.text();
      } else {
        throw new Error(`Status not 200: ${response.status}`);
      }
    }).then(function(rawXmlText) {
      return new DOMParser().parseFromString(rawXmlText, XML_MIME);
    }).then(function(rawXml) {
      const top2 = rawXml.documentElement;
      if (!top2) {
        throw new Error("documentElement in xml from DOMParser is null.");
      }
      const contributorArray = top2.getElementsByTagName("Contributor");
      const out = [];
      if (contributorArray) {
        for (let i = 0; i < contributorArray.length; i++) {
          const item = contributorArray.item(i);
          if (item && isDef(item.textContent)) {
            out.push(item.textContent);
          }
        }
      }
      return out;
    });
  }
  /**
   * Forms the URL to get version from the web service, without any query paramters
   *
   * @returns the url
   */
  formVersionURL() {
    return appendToPath(this.formBaseURL(), "version");
  }
  /**
   * Queries the remote web service to get its version
   *
   * @returns Promise to version string
   */
  queryVersion() {
    const url2 = this.formVersionURL();
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then(
      (response) => {
        if (response.status === 200) {
          return response.text();
        } else {
          throw new Error(`Status not 200: ${response.status}`);
        }
      }
    );
  }
  /**
   * Form URL to query the remote web service, encoding the query parameters.
   *
   * @returns url
   */
  formURL() {
    let url2 = appendToPath(this.formBaseURL(), "query?");
    if (this._eventId) {
      url2 = url2 + makeParam("eventid", this._eventId);
    }
    if (this._startTime) {
      url2 = url2 + makeParam("starttime", toIsoWoZ(this._startTime));
    }
    if (this._endTime) {
      url2 = url2 + makeParam("endtime", toIsoWoZ(this._endTime));
    }
    if (isNumArg(this._minMag)) {
      url2 = url2 + makeParam("minmag", this._minMag);
    }
    if (isNumArg(this._maxMag)) {
      url2 = url2 + makeParam("maxmag", this._maxMag);
    }
    if (isStringArg(this._magnitudeType)) {
      url2 = url2 + makeParam("magnitudetype", this._magnitudeType);
    }
    if (isNumArg(this._minDepth)) {
      url2 = url2 + makeParam("mindepth", this._minDepth);
    }
    if (isNumArg(this._maxDepth)) {
      url2 = url2 + makeParam("maxdepth", this._maxDepth);
    }
    if (isNumArg(this._minLat)) {
      url2 = url2 + makeParam("minlat", this._minLat);
    }
    if (isNumArg(this._maxLat)) {
      url2 = url2 + makeParam("maxlat", this._maxLat);
    }
    if (isNumArg(this._minLon)) {
      url2 = url2 + makeParam("minlon", this._minLon);
    }
    if (isNumArg(this._maxLon)) {
      url2 = url2 + makeParam("maxlon", this._maxLon);
    }
    if (isNumArg(this._minRadius) || isNumArg(this._maxRadius)) {
      if (isNumArg(this._latitude) && isNumArg(this._longitude)) {
        url2 = url2 + makeParam("latitude", this._latitude) + makeParam("longitude", this._longitude);
        if (isNumArg(this._minRadius)) {
          url2 = url2 + makeParam("minradius", this._minRadius);
        }
        if (isNumArg(this._maxRadius)) {
          url2 = url2 + makeParam("maxradius", this._maxRadius);
        }
      } else {
        throw new Error(
          `Cannot use minRadius or maxRadius without latitude and longitude: lat=${this._latitude} lon= ${this._longitude}`
        );
      }
    }
    if (this._includeArrivals) {
      if (this._host !== USGS_HOST) {
        url2 = url2 + "includearrivals=true&";
      } else {
        if (this._eventId) {
        } else {
          throw new Error(
            "USGS host, earthquake.usgs.gov, does not support includearrivals parameter."
          );
        }
      }
    }
    if (isObject(this._updatedAfter)) {
      url2 = url2 + makeParam("updatedafter", this._updatedAfter);
    }
    if (isDef(this._includeAllOrigins)) {
      url2 = url2 + makeParam("includeallorigins", this._includeAllOrigins);
    }
    if (isDef(this._includeAllMagnitudes)) {
      url2 = url2 + makeParam("includeallmagnitudes", this._includeAllMagnitudes);
    }
    if (isStringArg(this._format)) {
      url2 = url2 + makeParam("format", this._format);
    }
    if (isNumArg(this._limit)) {
      url2 = url2 + makeParam("limit", this._limit);
    }
    if (isNumArg(this._offset)) {
      url2 = url2 + makeParam("offset", this._offset);
    }
    if (isStringArg(this._orderBy)) {
      url2 = url2 + makeParam("orderby", this._orderBy);
    }
    if (isStringArg(this._catalog)) {
      url2 = url2 + makeParam("catalog", this._catalog);
    }
    if (isStringArg(this._contributor)) {
      url2 = url2 + makeParam("contributor", this._contributor);
    }
    if (isDef(this._nodata)) {
      url2 = url2 + makeParam("nodata", this._nodata);
    }
    if (url2.endsWith("&") || url2.endsWith("?")) {
      url2 = url2.substr(0, url2.length - 1);
    }
    return url2;
  }
};

// src/fdsnstation.mts
var fdsnstation_exports = {};
__export(fdsnstation_exports, {
  EARTHSCOPE_HOST: () => EARTHSCOPE_HOST,
  IRIS_HOST: () => IRIS_HOST,
  LEVELS: () => LEVELS,
  LEVEL_CHANNEL: () => LEVEL_CHANNEL,
  LEVEL_NETWORK: () => LEVEL_NETWORK,
  LEVEL_RESPONSE: () => LEVEL_RESPONSE,
  LEVEL_STATION: () => LEVEL_STATION,
  SERVICE_NAME: () => SERVICE_NAME4,
  SERVICE_VERSION: () => SERVICE_VERSION4,
  STATION_SERVICE: () => STATION_SERVICE,
  StationQuery: () => StationQuery
});
var LEVEL_NETWORK = "network";
var LEVEL_STATION = "station";
var LEVEL_CHANNEL = "channel";
var LEVEL_RESPONSE = "response";
var LEVELS = [
  LEVEL_NETWORK,
  LEVEL_STATION,
  LEVEL_CHANNEL,
  LEVEL_RESPONSE
];
var STATION_SERVICE = "station";
var SERVICE_VERSION4 = 1;
var SERVICE_NAME4 = `fdsnws-station-${SERVICE_VERSION4}`;
var StationQuery = class extends FDSNCommon {
  /**
   * Construct a query
   *
   * @param host the host to connect to , defaults to service.earthscope.org
   */
  constructor(host) {
    super(STATION_SERVICE, host);
  }
  /**
   * Gets/Sets the version of the fdsnws spec, 1 is currently the only value.
   * Setting this is probably a bad idea as the code may not be compatible with
   * the web service.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  specVersion(value) {
    doStringGetterSetter(this, "specVersion", value);
    return this;
  }
  getSpecVersion() {
    return this._specVersion;
  }
  /**
   * Gets/Sets the protocol, http or https. This should match the protocol
   * of the page loaded, but is autocalculated and generally need not be set.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  protocol(value) {
    doStringGetterSetter(this, "protocol", value);
    return this;
  }
  getProtocol() {
    return this._protocol;
  }
  /**
   * Gets/Sets the remote host to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  host(value) {
    doStringGetterSetter(this, "host", value);
    return this;
  }
  getHost() {
    return this._host;
  }
  /**
   * Gets/Sets the remote port to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  port(value) {
    doIntGetterSetter(this, "port", value);
    return this;
  }
  getPort() {
    return this._port;
  }
  pathBase(value) {
    doStringGetterSetter(this, "path_base", value);
    return this;
  }
  getPathBase() {
    return this._path_base;
  }
  /**
   * Gets/Sets the nodata parameter, usually 404 or 204 (default), controlling
   * the status code when no matching data is found by the service.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  nodata(value) {
    doIntGetterSetter(this, "nodata", value);
    return this;
  }
  getNodata() {
    return this._nodata;
  }
  /**
   * Get/Set the network query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  networkCode(value) {
    doStringGetterSetter(this, "networkCode", value);
    return this;
  }
  getNetworkCode() {
    return this._networkCode;
  }
  /**
   * Get/Set the station query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  stationCode(value) {
    doStringGetterSetter(this, "stationCode", value);
    return this;
  }
  getStationCode() {
    return this._stationCode;
  }
  /**
   * Get/Set the location code query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  locationCode(value) {
    doStringGetterSetter(this, "locationCode", value);
    return this;
  }
  getLocationCode() {
    return this._locationCode;
  }
  /**
   * Get/Set the channel query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  channelCode(value) {
    doStringGetterSetter(this, "channelCode", value);
    return this;
  }
  getChannelCode() {
    return this._channelCode;
  }
  /**
   * Get/Set the starttime query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  startTime(value) {
    doMomentGetterSetter(this, "startTime", value);
    return this;
  }
  getStartTime() {
    return this._startTime;
  }
  /**
   * Get/Set the endtime query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  endTime(value) {
    doMomentGetterSetter(this, "endTime", value);
    return this;
  }
  getEndTime() {
    return this._endTime;
  }
  /**
   * Sets startTime and endTime using the given time window
   *
   * @param   se time window
   * @returns     this
   */
  timeRange(se) {
    this.startTime(validStartTime(se));
    this.endTime(validEndTime(se));
    return this;
  }
  /**
   * Get/Set the startbefore query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  startBefore(value) {
    doMomentGetterSetter(this, "startBefore", value);
    return this;
  }
  getStartBefore() {
    return this._startBefore;
  }
  /**
   * Get/Set the endbefore query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  endBefore(value) {
    doMomentGetterSetter(this, "endBefore", value);
    return this;
  }
  getEndBefore() {
    return this._endBefore;
  }
  /**
   * Get/Set the startafter query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  startAfter(value) {
    doMomentGetterSetter(this, "startAfter", value);
    return this;
  }
  getStartAfter() {
    return this._startAfter;
  }
  /**
   * Get/Set the endafter query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  endAfter(value) {
    doMomentGetterSetter(this, "endAfter", value);
    return this;
  }
  getEndAfter() {
    return this._endAfter;
  }
  /**
   * Get/Set the minlat query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minLat(value) {
    doFloatGetterSetter(this, "minLat", value);
    return this;
  }
  getMinLat() {
    return this._minLat;
  }
  /**
   * Get/Set the maxlon query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  maxLat(value) {
    doFloatGetterSetter(this, "maxLat", value);
    return this;
  }
  getMaxLat() {
    return this._maxLat;
  }
  /**
   * Get/Set the minlon query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minLon(value) {
    doFloatGetterSetter(this, "minLon", value);
    return this;
  }
  getMinLon() {
    return this._minLon;
  }
  /**
   * Get/Set the maxlon query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  maxLon(value) {
    doFloatGetterSetter(this, "maxLon", value);
    return this;
  }
  getMaxLon() {
    return this._maxLon;
  }
  /**
   * Get/Set the latitude query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  latitude(value) {
    doFloatGetterSetter(this, "latitude", value);
    return this;
  }
  getLatitude() {
    return this._latitude;
  }
  /**
   * Get/Set the longitude query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  longitude(value) {
    doFloatGetterSetter(this, "longitude", value);
    return this;
  }
  getLongitude() {
    return this._longitude;
  }
  /**
   * Get/Set the minradius query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minRadius(value) {
    doFloatGetterSetter(this, "minRadius", value);
    return this;
  }
  getMinRadius() {
    return this._minRadius;
  }
  /**
   * Get/Set the maxradius query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  maxRadius(value) {
    doFloatGetterSetter(this, "maxRadius", value);
    return this;
  }
  getMaxRadius() {
    return this._maxRadius;
  }
  /**
   * Get/Set the includerestricted query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  includeRestricted(value) {
    doBoolGetterSetter(this, "includeRestricted", value);
    return this;
  }
  getIncludeRestricted() {
    return this._includeRestricted;
  }
  /**
   * Get/Set the includeavailability query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  includeAvailability(value) {
    doBoolGetterSetter(this, "includeAvailability", value);
    return this;
  }
  getIncludeAvailability() {
    return this._includeAvailability;
  }
  /**
   * Get/Set the format query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  format(value) {
    doStringGetterSetter(this, "format", value);
    return this;
  }
  getFormat() {
    return this._format;
  }
  /**
   * Get/Set the updatedafter query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  updatedAfter(value) {
    doMomentGetterSetter(this, "updatedAfter", value);
    return this;
  }
  getUpdatedAfter() {
    return this._updatedAfter;
  }
  /**
   * Get/Set the matchtimeseries query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  matchTimeseries(value) {
    doBoolGetterSetter(this, "matchTimeseries", value);
    return this;
  }
  getMatchTimeseries() {
    return this._matchTimeseries;
  }
  latLonRegion(value) {
    if (value instanceof LatLonBox) {
      this._minLat = value.south;
      this._maxLat = value.north;
      this._minLon = value.west;
      this._maxLon = value.east;
      this._latitude = void 0;
      this._longitude = void 0;
      this._minRadius = void 0;
      this._maxRadius = void 0;
    } else if (value instanceof LatLonRadius) {
      this._latitude = value.latitude;
      this._longitude = value.longitude;
      this._minRadius = value.minRadius;
      this._maxRadius = value.maxRadius;
      this._minLat = void 0;
      this._maxLat = void 0;
      this._minLon = void 0;
      this._maxLon = void 0;
    } else if (!isDef(value)) {
      this._latitude = void 0;
      this._longitude = void 0;
      this._minRadius = void 0;
      this._maxRadius = void 0;
      this._minLat = void 0;
      this._maxLat = void 0;
      this._minLon = void 0;
      this._maxLon = void 0;
    } else {
      throw new Error(
        `value argument is optional or LatLonRegion, but was type ${typeof value}, '${stringify(value)}' `
      );
    }
    return this;
  }
  nslcCodes(channelId) {
    this.networkCode(channelId.networkCode);
    this.stationCode(channelId.stationCode);
    this.locationCode(channelId.locationCode);
    this.channelCode(channelId.channelCode);
    return this;
  }
  /**
   * Get/Set the timeout in seconds for the request. Default is 30.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  timeout(value) {
    doFloatGetterSetter(this, "timeoutSec", value);
    return this;
  }
  getTimeout() {
    return this._timeoutSec;
  }
  /**
   * Checks to see if any parameter that would limit the data
   * returned is set. This is a crude, coarse check to make sure
   * the client doesn't ask for EVERYTHING the server has.
   *
   * @returns true if some parameter set
   */
  isSomeParameterSet() {
    return isDef(this._networkCode) && this._networkCode.length > 0 && this._networkCode !== "*" || isDef(this._stationCode) && this._stationCode.length > 0 && this._stationCode !== "*" || isDef(this._locationCode) && this._locationCode.length > 0 && this._locationCode !== "*" || isDef(this._channelCode) && this._channelCode.length > 0 && this._channelCode !== "*" || isDef(this._startTime) || isDef(this._endTime) || isDef(this._startBefore) || isDef(this._endBefore) || isDef(this._startAfter) || isDef(this._endAfter) || isDef(this._minLat) || isDef(this._maxLat) || isDef(this._minLon) || isDef(this._maxLon) || isDef(this._latitude) || isDef(this._longitude) || isDef(this._minRadius) || isDef(this._maxRadius) || isDef(this._updatedAfter);
  }
  /**
   * Queries the remote web service for networks.
   *
   * @returns a Promise to an Array of Network objects.
   */
  queryNetworks() {
    return this.query(LEVEL_NETWORK);
  }
  /**
   * Queries the remote web service for stations. The stations
   * are contained within their respective Networks.
   *
   * @returns a Promise to an Array of Network objects.
   */
  queryStations() {
    return this.query(LEVEL_STATION);
  }
  /**
   * Queries the remote web service for channels. The Channels
   * are contained within their respective Stations which are in Networks.
   *
   * @returns a Promise to an Array of Network objects.
   */
  queryChannels() {
    return this.query(LEVEL_CHANNEL);
  }
  /**
   * Queries the remote web service for responses. The Responses
   * are contained within their respective Channels,
   * which are in Stations which are in Networks.
   *
   * @returns a Promise to an Array of Network objects.
   */
  queryResponses() {
    return this.query(LEVEL_RESPONSE);
  }
  /**
   * Queries the remote web service at the given level.
   *
   * @param level the level to query at, networ, station, channel or response.
   * @returns a Promise to an Array of Network objects.
   */
  query(level) {
    if (!LEVELS.includes(level)) {
      throw new Error("Unknown level: '" + level + "'");
    }
    return this.queryRawXml(level).then(function(rawXml) {
      return parseStationXml(rawXml);
    });
  }
  /**
   * Execute POST request for networks, using params defined in this, and with
   * channel lines of the form:
   *
   * NET STA LOC CHA STARTTIME ENDTIME
   *
   * Note that empty LOC should be encoded as dash-dash
   *
   * @param  postLines array of channel selection lines
   * @returns a Promise to an Array of Network objects.
   */
  postQueryNetworks(postLines) {
    return this.postQueryRawXml(LEVEL_NETWORK, postLines).then(
      function(rawXml) {
        return parseStationXml(rawXml);
      }
    );
  }
  /**
   * Execute POST request for stations, using params defined in this, and with
   * channel lines of the form:
   *
   * NET STA LOC CHA STARTTIME ENDTIME
   *
   * Note that empty LOC should be encoded as dash-dash
   *
   * @param  postLines array of channel selection lines
   * @returns a Promise to an Array of Network objects.
   */
  postQueryStations(postLines) {
    return this.postQueryRawXml(LEVEL_STATION, postLines).then(
      function(rawXml) {
        return parseStationXml(rawXml);
      }
    );
  }
  /**
   * Execute POST request for channels, using params defined in this, and with
   * channel lines of the form:
   *
   * NET STA LOC CHA STARTTIME ENDTIME
   *
   * Note that empty LOC should be encoded as dash-dash
   *
   * @param  postLines array of channel selection lines
   * @returns a Promise to an Array of Network objects.
   */
  postQueryChannels(postLines) {
    return this.postQueryRawXml(LEVEL_CHANNEL, postLines).then(
      function(rawXml) {
        return parseStationXml(rawXml);
      }
    );
  }
  /**
   * Execute POST request for responses, using params defined in this, and with
   * channel lines of the form:
   *
   * NET STA LOC CHA STARTTIME ENDTIME
   *
   * Note that empty LOC should be encoded as dash-dash
   *
   * @param  postLines array of channel selection lines
   * @returns a Promise to an Array of Network objects.
   */
  postQueryResponses(postLines) {
    return this.postQueryRawXml(LEVEL_RESPONSE, postLines).then(
      function(rawXml) {
        return parseStationXml(rawXml);
      }
    );
  }
  /**
   * Execute POST request using params defined in this, for given level, and with
   * channel lines of the form:
   *
   * NET STA LOC CHA STARTTIME ENDTIME
   *
   * Note that empty LOC should be encoded as dash-dash
   *
   * @param  level     level to request, one of network, station, channel, response
   * @param  postLines array of channel selection lines
   * @returns a Promise to an Array of Network objects.
   */
  postQuery(level, postLines) {
    if (!LEVELS.includes(level)) {
      throw new Error("Unknown level: '" + level + "'");
    }
    return this.postQueryRawXml(level, postLines).then(function(rawXml) {
      return parseStationXml(rawXml);
    });
  }
  /**
   * Queries the remote web service at the given level for raw xml.
   * Note that in the case of a nodata status code, xml that represents a
   * valid stationxml but with zero &lt;Network&gt; elements will be returned
   * as this simplifies parsing.
   *
   * @param level the level to query at, network, station, channel or response.
   * @returns a Promise to an xml Document.
   */
  queryRawXml(level) {
    return this.queryRawXmlText(level).then(function(rawXmlText) {
      return new DOMParser().parseFromString(rawXmlText, "text/xml");
    });
  }
  /**
   * Queries the remote web service at the given level for unparsed xml as text.
   * Note that in the case of a nodata status code, text that represents a
   * valid stationxml but with zero &lt;Network&gt; elements will be returned
   * as this simplifies parsing.
   *
   * @param level the level to query at, network, station, channel or response.
   * @returns a Promise to string.
   */
  queryRawXmlText(level) {
    if (!this.isSomeParameterSet()) {
      throw new Error(
        "Must set some parameter to avoid asking for everything."
      );
    }
    const url2 = this.formURL(level);
    const fetchInit = defaultFetchInitObj(XML_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then(
      (response) => {
        if (response.status === 200) {
          return response.text();
        } else if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
          return FAKE_EMPTY_XML;
        } else {
          throw new Error(`Status not successful: ${response.status}`);
        }
      }
    );
  }
  /**
   * Execute POST request using params defined in this, for given level, and with
   * channel lines of the form:
   *
   * NET STA LOC CHA STARTTIME ENDTIME
   *
   * Note that empty LOC should be encoded as dash-dash
   *
   * @param  level     level to request, one of network, station, channel, response
   * @param  postLines array of channel selection lines
   * @returns           string suitable for POST to fdsn station web service.
   */
  postQueryRawXml(level, postLines) {
    if (postLines.length === 0) {
      return Promise.resolve(FAKE_EMPTY_XML).then(function(rawXmlText) {
        return new DOMParser().parseFromString(rawXmlText, "text/xml");
      });
    } else {
      const fetchInit = defaultFetchInitObj(XML_MIME);
      fetchInit.method = "POST";
      fetchInit.body = this.createPostBody(level, postLines);
      return doFetchWithTimeout(
        this.formPostURL(),
        fetchInit,
        this._timeoutSec * 1e3
      ).then((response) => {
        if (response.status === 200) {
          return response.text();
        } else if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
          return FAKE_EMPTY_XML;
        } else {
          throw new Error(`Status not successful: ${response.status}`);
        }
      }).then(function(rawXmlText) {
        return new DOMParser().parseFromString(rawXmlText, "text/xml");
      });
    }
  }
  /**
   * Creates post body using params defined in this, for given level, and with
   * optional channel lines of the form:
   *
   * NET STA LOC CHA STARTTIME ENDTIME
   *
   * Note that empty LOC should be encoded as dash-dash
   *
   * @param  level     level to request, one of network, station, channel, response
   * @param  postLines optional array of channel selection lines
   * @returns           string suitable for POST to fdsn station web service.
   */
  createPostBody(level, postLines = []) {
    let out = "";
    if (!isStringArg(level)) {
      throw new Error(
        "level not specified, should be one of network, station, channel, response."
      );
    }
    out = out + makePostParam("level", level);
    if (isObject(this._startBefore)) {
      out = out + makePostParam("startbefore", toIsoWoZ(this._startBefore));
    }
    if (isObject(this._startAfter)) {
      out = out + makePostParam("startafter", toIsoWoZ(this._startAfter));
    }
    if (isObject(this._endBefore)) {
      out = out + makePostParam("endbefore", toIsoWoZ(this._endBefore));
    }
    if (isObject(this._endAfter)) {
      out = out + makePostParam("endafter", toIsoWoZ(this._endAfter));
    }
    if (isNumArg(this._minLat)) {
      out = out + makePostParam("minlat", this._minLat);
    }
    if (isNumArg(this._maxLat)) {
      out = out + makePostParam("maxlat", this._maxLat);
    }
    if (isNumArg(this._minLon)) {
      out = out + makePostParam("minlon", this._minLon);
    }
    if (isNumArg(this._maxLon)) {
      out = out + makePostParam("maxlon", this._maxLon);
    }
    if (isNumArg(this._latitude)) {
      out = out + makePostParam("lat", this._latitude);
    }
    if (isNumArg(this._longitude)) {
      out = out + makePostParam("lon", this._longitude);
    }
    if (isNumArg(this._minRadius)) {
      out = out + makePostParam("minradius", this._minRadius);
    }
    if (isNumArg(this._maxRadius)) {
      out = out + makePostParam("maxradius", this._maxRadius);
    }
    if (isDef(this._includeRestricted)) {
      out = out + makePostParam("includerestricted", this._includeRestricted);
    }
    if (isDef(this._includeAvailability)) {
      out = out + makePostParam("includeavailability", this._includeAvailability);
    }
    if (isObject(this._updatedAfter)) {
      out = out + makePostParam("updatedafter", toIsoWoZ(this._updatedAfter));
    }
    if (isDef(this._matchTimeseries)) {
      out = out + makePostParam("matchtimeseries", this._matchTimeseries);
    }
    if (isStringArg(this._format)) {
      out = out + makePostParam("format", this._format);
    }
    if (isNumArg(this._nodata)) {
      out = out + makePostParam("nodata", this._nodata);
    }
    postLines.forEach((line) => out = out + line.trim() + "\n");
    return out;
  }
  /**
   * Forms the URL to get version from the web service, without any query paramters
   *
   * @returns the url
   */
  formVersionURL() {
    return appendToPath(this.formBaseURL(), "version");
  }
  /**
   * Queries the remote web service to get its version
   *
   * @returns Promise to version string
   */
  queryVersion() {
    const url2 = this.formVersionURL();
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then(
      (response) => {
        if (response.status === 200) {
          return response.text();
        } else {
          throw new Error(`Status not 200: ${response.status}`);
        }
      }
    );
  }
  /**
   * Forms the basic URL to contact the web service, without any query paramters
   *
   * @returns the url
   */
  formBaseURL() {
    let colon = ":";
    const protocol = protocolForKnownHost(this._host, this._protocol);
    if (protocol.endsWith(colon)) {
      colon = "";
    }
    const port = this.defaultPortStringForProtocol(protocol);
    const path2 = `${this._path_base}/${this._service}/${this._specVersion}`;
    return `${protocol}${colon}//${this._host}${port}/${path2}`;
  }
  formPostURL() {
    return appendToPath(this.formBaseURL(), "query");
  }
  /**
   * Form URL to query the remote web service, encoding the query parameters.
   *
   * @param level network, station, channel or response
   * @returns url
   */
  formURL(level) {
    let url2 = appendToPath(this.formBaseURL(), "query?");
    if (!isStringArg(level)) {
      throw new Error(
        "level not specified, should be one of network, station, channel, response."
      );
    }
    url2 = url2 + makeParam("level", level);
    if (isStringArg(this._networkCode) && this._networkCode.length > 0 && this._networkCode !== "*") {
      url2 = url2 + makeParam("net", this._networkCode);
    }
    if (isStringArg(this._stationCode) && this._stationCode.length > 0 && this._stationCode !== "*") {
      url2 = url2 + makeParam("sta", this._stationCode);
    }
    if (isStringArg(this._locationCode) && this._locationCode.length > 0 && this._locationCode !== "*") {
      url2 = url2 + makeParam("loc", this._locationCode);
    }
    if (isStringArg(this._channelCode) && this._channelCode.length > 0 && this._channelCode !== "*") {
      url2 = url2 + makeParam("cha", this._channelCode);
    }
    if (isObject(this._startTime)) {
      url2 = url2 + makeParam("starttime", toIsoWoZ(this._startTime));
    }
    if (isObject(this._endTime)) {
      url2 = url2 + makeParam("endtime", toIsoWoZ(this._endTime));
    }
    if (isObject(this._startBefore)) {
      url2 = url2 + makeParam("startbefore", toIsoWoZ(this._startBefore));
    }
    if (isObject(this._startAfter)) {
      url2 = url2 + makeParam("startafter", toIsoWoZ(this._startAfter));
    }
    if (isObject(this._endBefore)) {
      url2 = url2 + makeParam("endbefore", toIsoWoZ(this._endBefore));
    }
    if (isObject(this._endAfter)) {
      url2 = url2 + makeParam("endafter", toIsoWoZ(this._endAfter));
    }
    if (isNumArg(this._minLat)) {
      url2 = url2 + makeParam("minlat", this._minLat);
    }
    if (isNumArg(this._maxLat)) {
      url2 = url2 + makeParam("maxlat", this._maxLat);
    }
    if (isNumArg(this._minLon)) {
      url2 = url2 + makeParam("minlon", this._minLon);
    }
    if (isNumArg(this._maxLon)) {
      url2 = url2 + makeParam("maxlon", this._maxLon);
    }
    if (isNumArg(this._latitude)) {
      url2 = url2 + makeParam("lat", this._latitude);
    }
    if (isNumArg(this._longitude)) {
      url2 = url2 + makeParam("lon", this._longitude);
    }
    if (isNumArg(this._minRadius)) {
      url2 = url2 + makeParam("minradius", this._minRadius);
    }
    if (isNumArg(this._maxRadius)) {
      url2 = url2 + makeParam("maxradius", this._maxRadius);
    }
    if (isDef(this._includeRestricted)) {
      url2 = url2 + makeParam("includerestricted", this._includeRestricted);
    }
    if (isDef(this._includeAvailability)) {
      url2 = url2 + makeParam("includeavailability", this._includeAvailability);
    }
    if (isObject(this._updatedAfter)) {
      url2 = url2 + makeParam("updatedafter", toIsoWoZ(this._updatedAfter));
    }
    if (isDef(this._matchTimeseries)) {
      url2 = url2 + makeParam("matchtimeseries", this._matchTimeseries);
    }
    if (isStringArg(this._format)) {
      url2 = url2 + makeParam("format", this._format);
    }
    if (isNumArg(this._nodata)) {
      url2 = url2 + makeParam("nodata", this._nodata);
    }
    if (url2.endsWith("&") || url2.endsWith("?")) {
      url2 = url2.substr(0, url2.length - 1);
    }
    return url2;
  }
};

// src/fdsndatacenters.mts
var DATACENTERS_SERVICE = "datacenters";
var DATACENTERS_PATH_BASE = "ws";
var DataCentersQuery = class extends FDSNCommon {
  constructor(host) {
    if (!isNonEmptyStringArg(host)) {
      host = FDSN_HOST;
    }
    super(DATACENTERS_SERVICE, host);
    this._path_base = DATACENTERS_PATH_BASE;
  }
  /**
   * Gets/Sets the version of the fdsnws spec, 1 is currently the only value.
   * Setting this is probably a bad idea as the code may not be compatible with
   * the web service.
   *
   * @param value optional new value if setting
   * @returns the query when setting, the current value os services if no arguments
   */
  specVersion(value) {
    doStringGetterSetter(this, "specVersion", value);
    return this;
  }
  getSpecVersion() {
    return this._specVersion;
  }
  /**
   * Gets/Sets the protocol, http or https. This should match the protocol
   * of the page loaded, but is autocalculated and generally need not be set.
   *
   * @param value optional new value if setting
   * @returns the query when setting, the current value os services if no arguments
   */
  protocol(value) {
    doStringGetterSetter(this, "protocol", value);
    return this;
  }
  getProtocol() {
    return this._protocol;
  }
  /**
   * Gets/Sets the remote host to connect to. This defaults to
   * www.fdsn.org and generally should not be set.
   *
   * @param value optional new value if setting
   * @returns the query when setting, the current value os services if no arguments
   */
  host(value) {
    doStringGetterSetter(this, "host", value);
    return this;
  }
  getHost() {
    return this._host;
  }
  /**
   * Gets/Sets the remote port to connect to. This defaults to
   * the standard port for the protocol and generally should not be set.
   *
   * @param value optional new value if setting
   * @returns the query when setting, the current value os services if no arguments
   */
  port(value) {
    doIntGetterSetter(this, "port", value);
    return this;
  }
  getPort() {
    return this._port;
  }
  pathBase(value) {
    doStringGetterSetter(this, "path_base", value);
    return this;
  }
  getPathBase() {
    return this._path_base;
  }
  /**
   * limits results to the named data center, default is all data centers
   *
   * @param   value names to search for
   * @returns the query when setting, the current value os services if no arguments
   */
  name(value) {
    doStringGetterSetter(this, "name", value);
    return this;
  }
  getName() {
    return this._name;
  }
  /**
   * limits results to services that match the glob style pattern
   *
   * @param  value glob style pattern to match against
   * @returns the query when setting, the current value os services if no arguments
   */
  services(value) {
    doStringGetterSetter(this, "services", value);
    return this;
  }
  getServices() {
    return this._services;
  }
  /**
   * whether the results include detailed information about
   * the data sets offered by each center, default is false
   *
   * @param  value true to include datasets
   * @returns the query when setting, the current value os services if no arguments
   */
  includeDataSets(value) {
    doBoolGetterSetter(this, "includedatasets", value);
    return this;
  }
  getIncludeDataSets() {
    return this._includedatasets;
  }
  /**
   * Get/Set the timeout in seconds for the request. Default is 30.
   *
   * @param  value timeout seconds
   * @returns the query when setting, the current value os services if no arguments
   */
  timeout(value) {
    doFloatGetterSetter(this, "timeoutSec", value);
    return this;
  }
  getTimeout() {
    return this._timeoutSec;
  }
  /**
   * queries the fdsn registry web service, returning the result as a parsed json object.
   *
   * @returns Promise to the json object.
   */
  queryJson() {
    const url2 = this.formURL();
    const fetchInit = defaultFetchInitObj(JSON_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      const contentType = response.headers.get("content-type");
      if (isNonEmptyStringArg(contentType) && contentType.includes(JSON_MIME)) {
        return response.json();
      }
      throw new TypeError(`Oops, we did not get JSON! ${contentType}`);
    }).then((jsonValue) => {
      if (isValidRootType2(jsonValue)) {
        return jsonValue;
      } else {
        throw new TypeError(`Oops, we did not get roottype JSON!`);
      }
    });
  }
  /**
   * queries the registry to find fdsn availability compatible web services within
   * a datacenter of the given name, optionally within the repository with
   * the repo name.
   *
   * @param   name     datacenter name
   * @param   repoName optional repository name
   * @returns           Promise to Array of fdsnavailability.AvailabilityQuery objects
   */
  findFdsnAvailability(name, repoName) {
    if (name && name.length > 0) {
      this.name(name);
    }
    this.services(SERVICE_NAME);
    return this.queryJson().then((json2) => {
      const out = this.extractCompatibleServices(
        json2,
        SERVICE_NAME,
        repoName
      );
      const sList = out.map((service) => {
        if ("url" in service && typeof service.url === "string") {
          const url2 = new URL(service.url);
          const q = new AvailabilityQuery(url2.hostname);
          if (url2.port && url2.port.length > 0) {
            q.port(Number.parseInt(url2.port));
          }
          return q;
        } else {
          return null;
        }
      });
      return sList.flatMap((f) => f ? [f] : []);
    });
  }
  /**
   * queries the registry to find fdsn dataselect compatible web services within
   * a datacenter of the given name, optionally within the repository with
   * the repo name.
   *
   * @param   name     datacenter name
   * @param   repoName optional repository name
   * @returns           Promise to Array of fdsndataselect.DataSelectQuery objects
   */
  findFdsnDataSelect(name, repoName) {
    if (name && name.length > 0) {
      this.name(name);
    }
    this.services(SERVICE_NAME2);
    return this.queryJson().then((json2) => {
      const out = this.extractCompatibleServices(
        json2,
        SERVICE_NAME2,
        repoName
      );
      const sList = out.map((service) => {
        if ("url" in service && typeof service.url === "string") {
          const url2 = new URL(service.url);
          const q = new DataSelectQuery(url2.hostname);
          if (url2.port && url2.port.length > 0) {
            q.port(Number.parseInt(url2.port));
          }
          return q;
        } else {
          return null;
        }
      });
      return sList.flatMap((f) => f ? [f] : []);
    });
  }
  /**
   * queries the registry to find a fdsn event compatible web services within
   * a datacenter of the given name, optionally within the repository with
   * the repo name.
   *
   * @param   dcname     datacenter name
   * @param   repoName optional repository name
   * @returns           Promise to Array of fdsnevent.EventQuery objects
   */
  findFdsnEvent(dcname, repoName) {
    if (dcname && dcname.length > 0) {
      this.name(dcname);
    }
    this.services(SERVICE_NAME3);
    return this.queryJson().then((json2) => {
      const out = this.extractCompatibleServices(
        json2,
        SERVICE_NAME3,
        repoName
      );
      const sList = out.map((service) => {
        if ("url" in service && typeof service.url === "string") {
          const url2 = new URL(service.url);
          const q = new EventQuery(url2.hostname);
          if (url2.port && url2.port.length > 0) {
            q.port(Number.parseInt(url2.port));
          }
          return q;
        } else {
          return null;
        }
      });
      return sList.flatMap((f) => f ? [f] : []);
    });
  }
  /**
   * queries the registry to find a fdsn station compatible web services within
   * a datacenter of the given name, optionally within the repository with
   * the repo name.
   *
   * @param   dcname     datacenter name
   * @param   repoName optional repository name
   * @returns           Promise to Array of fdsnstation.StationQuery objects
   */
  findFdsnStation(dcname, repoName) {
    if (dcname && dcname.length > 0) {
      this.name(dcname);
    }
    this.services(SERVICE_NAME4);
    return this.queryJson().then((json2) => {
      const out = this.extractCompatibleServices(
        json2,
        SERVICE_NAME4,
        repoName
      );
      const sList = out.map((service) => {
        if ("url" in service && typeof service.url === "string") {
          const url2 = new URL(service.url);
          const q = new StationQuery(url2.hostname);
          if (url2.port && url2.port.length > 0) {
            q.port(Number.parseInt(url2.port));
          }
          return q;
        } else {
          return null;
        }
      });
      return sList.flatMap((f) => f ? [f] : []);
    });
  }
  /**
   * Extracts services comaptible with the given service name, optionally within
   * the given repository, from the json.
   *
   * @param   json           json containing services
   * @param   compatibleName service name to be compatible with
   * @param   repoName       optional repository within the json to search
   * @returns                array of services found
   */
  extractCompatibleServices(json2, compatibleName, repoName) {
    const out = [];
    json2.datacenters.forEach((dc) => {
      dc.repositories.forEach((repo) => {
        if (!isDef(repoName) || repoName === repo.name) {
          repo.services.forEach((service) => {
            if (service.name === compatibleName || isDef(service.compatibleWith) && service.compatibleWith.includes(compatibleName)) {
              out.push(service);
            }
          });
        }
      });
    });
    return out;
  }
  /**
   * Forms the base of the url for accessing the datacenters service.
   *
   * @returns         URL as string
   */
  formBaseURL() {
    let colon = ":";
    const protocol = protocolForKnownHost(this._host, this._protocol);
    if (protocol.endsWith(colon)) {
      colon = "";
    }
    const port = this.defaultPortStringForProtocol(protocol);
    const path2 = `${this._path_base}/${this._service}/${this._specVersion}`;
    return `${protocol}${colon}//${this._host}${port}/${path2}`;
  }
  /**
   * Forms version url, not part of spec and so may not be supported.
   *
   * @returns         version
   */
  formVersionURL() {
    return appendToPath(this.formBaseURL(), "version");
  }
  /**
   * Queries the remote web service to get its version
   *
   * @returns Promise to version string
   */
  queryVersion() {
    const url2 = this.formVersionURL();
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then(
      (response) => {
        if (response.status === 200) {
          return response.text();
        } else {
          throw new Error(`Status not 200: ${response.status}`);
        }
      }
    );
  }
  /**
   * forms a url to the fdsn registry based on the configured parameters.
   *
   * @returns the url
   */
  formURL() {
    const method = "query";
    let url2 = appendToPath(this.formBaseURL(), `${method}?`);
    if (this._name) {
      url2 = url2 + makeParam("name", this._name);
    }
    if (this._services) {
      url2 = url2 + makeParam("services", this._services);
    }
    if (this._includedatasets) {
      url2 = url2 + makeParam("includedatasets", this._includedatasets);
    }
    if (url2.endsWith("&") || url2.endsWith("?")) {
      url2 = url2.substr(0, url2.length - 1);
    }
    return url2;
  }
};
function isValidRootType2(jsonValue) {
  if (!jsonValue || typeof jsonValue !== "object") {
    throw new TypeError("json is not object");
  }
  const jsonObj = jsonValue;
  if (Array.isArray(jsonObj.datacenters) && typeof jsonObj.version === "number") {
    return true;
  } else {
    throw new TypeError("json is not valid for FDSN DataCenters");
  }
}

// src/fdsneventcomponent.mts
var fdsneventcomponent_exports = {};
__export(fdsneventcomponent_exports, {
  EarthquakeSearch: () => EarthquakeSearch
});
var eqsearchHtml = `
<div class="wrapper">
  <div>
  <label>Time Range </label>
  <sp-timerange duration="P7D"></sp-timerange>
  <button id="now">Now</button></div>
  <div>
  <button id="today">Today</button>
  <button id="week">Week</button>
  <button id="month">Month</button>
  <button id="year">Year</button>
  </div>
  <div>
    <label>Geo:</label>
    <sp-latlon-choice></sp-latlon-choice>
  </div>
  <div><label>Magnitude</label><sp-minmax id="magnitude" min="-1" max="10"></sp-minmax></div>
  <div><label>Depth</label><sp-minmax id="depth" min="0" max="1000"></sp-minmax><label>km</label></div>
</div>
`;
var EarthquakeSearch = class extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: "open" });
    this.draw_element(shadow);
  }
  _registerEvent(wrapper, sel) {
    const component = wrapper.querySelector(sel);
    if (!component) {
      throw new Error(`can't find ${sel}`);
    }
    component.addEventListener(
      "change",
      () => this.dispatchEvent(new Event("change"))
    );
  }
  draw_element(shadow) {
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    wrapper.innerHTML = eqsearchHtml;
    shadow.appendChild(wrapper);
    this._registerEvent(wrapper, "sp-timerange");
    this._registerEvent(wrapper, "sp-latlon-choice");
    this._registerEvent(wrapper, "sp-minmax#magnitude");
    this._registerEvent(wrapper, "sp-minmax#depth");
    const trChooser = wrapper.querySelector("sp-timerange");
    if (!trChooser) {
      throw new Error("can't find sp-timerange");
    }
    if (this.hasAttribute("start")) {
      const s2 = this.getAttribute("start");
      if (s2 !== null) {
        trChooser.start = isoToDateTime(s2);
      }
    }
    if (this.hasAttribute("end")) {
      const e = this.getAttribute("end");
      if (e !== null) {
        trChooser.end = isoToDateTime(e);
      }
    }
    if (this.hasAttribute("duration")) {
      const d = this.getAttribute("duration");
      if (d !== null) {
        trChooser.duration = Duration.fromISO("" + d);
      }
    }
    const magChooser = wrapper.querySelector(
      "sp-minmax#magnitude"
    );
    if (!magChooser) {
      throw new Error("can't find sp-minmax#magnitude");
    }
    if (this.hasAttribute("mag-min")) {
      const m = this.getAttribute("mag-min");
      if (m !== null) {
        magChooser.min = parseFloat(m);
      }
    }
    if (this.hasAttribute("mag-max")) {
      const m = this.getAttribute("mag-max");
      if (m !== null) {
        magChooser.max = parseFloat(m);
      }
    }
    const depthChooser = wrapper.querySelector(
      "sp-minmax#depth"
    );
    if (!depthChooser) {
      throw new Error("can't find sp-minmax#depth");
    }
    if (this.hasAttribute("depth-min")) {
      const m = this.getAttribute("depth-min");
      if (m !== null) {
        depthChooser.min = parseFloat(m);
      }
    }
    if (this.hasAttribute("depth-max")) {
      const m = this.getAttribute("depth-max");
      if (m !== null) {
        depthChooser.max = parseFloat(m);
      }
    }
    const latlonChooser = wrapper.querySelector(
      "sp-latlon-choice"
    );
    if (!latlonChooser) {
      throw new Error("can't find sp-latlon-choice");
    }
    LatLonChoice.observedAttributes.forEach((attr) => {
      if (this.hasAttribute(attr)) {
        const attrVal = this.getAttribute(attr);
        if (attrVal) {
          latlonChooser.setAttribute(attr, attrVal);
        }
      }
    });
    const nowBtn = wrapper.querySelector("#now");
    if (!nowBtn) {
      throw new Error("can't find button#now");
    }
    nowBtn.addEventListener("click", (_event) => {
      trChooser.end = DateTime.utc();
    });
    const todayBtn = wrapper.querySelector("#today");
    if (!todayBtn) {
      throw new Error("can't find button#today");
    }
    todayBtn.addEventListener("click", (_event) => {
      trChooser.duration = Duration.fromISO("P1D");
    });
    const weekBtn = wrapper.querySelector("#week");
    if (!weekBtn) {
      throw new Error("can't find button#week");
    }
    weekBtn.addEventListener("click", (_event) => {
      trChooser.duration = Duration.fromISO("P7D");
    });
    const monthBtn = wrapper.querySelector("#month");
    if (!monthBtn) {
      throw new Error("can't find button#month");
    }
    monthBtn.addEventListener("click", (_event) => {
      trChooser.duration = Duration.fromISO("P1M");
    });
    const yearBtn = wrapper.querySelector("#year");
    if (!yearBtn) {
      throw new Error("can't find button#year");
    }
    yearBtn.addEventListener("click", (_event) => {
      trChooser.duration = Duration.fromISO("P1Y");
    });
  }
  populateQuery(query) {
    if (!query) {
      query = new EventQuery();
    }
    const wrapper = this.shadowRoot?.querySelector("div");
    const trChooser = wrapper.querySelector("sp-timerange");
    if (!trChooser) {
      throw new Error("can't find sp-timerange");
    }
    query.startTime(trChooser.start);
    query.endTime(trChooser.end);
    const latlonchoice = wrapper.querySelector(
      "sp-latlon-choice"
    );
    const choosenLatLon = latlonchoice.choosen();
    if (choosenLatLon instanceof LatLonBoxEl) {
      const latlonbox = choosenLatLon;
      if (latlonbox.south > -90) {
        query.minLat(latlonbox.south);
      }
      if (latlonbox.north < 90) {
        query.maxLat(latlonbox.north);
      }
      if (latlonbox.west > -180 && latlonbox.west + 360 !== latlonbox.east) {
        query.minLon(latlonbox.west);
      }
      if (latlonbox.east < 360 && latlonbox.west + 360 !== latlonbox.east) {
        query.maxLon(latlonbox.east);
      }
    } else if (choosenLatLon instanceof LatLonRadiusEl) {
      const latlonrad = choosenLatLon;
      if (latlonrad.minRadius > 0 || latlonrad.maxRadius < 180) {
        query.latitude(latlonrad.latitude);
        query.longitude(latlonrad.longitude);
        if (latlonrad.minRadius > 0) {
          query.minRadius(latlonrad.minRadius);
        }
        if (latlonrad.maxRadius < 180) {
          query.maxRadius(latlonrad.maxRadius);
        }
      }
    } else {
    }
    const mag = wrapper.querySelector("sp-minmax#magnitude");
    if (mag.min > 0) {
      query.minMag(mag.min);
    }
    if (mag.max < 10) {
      query.maxMag(mag.max);
    }
    const depth = wrapper.querySelector("sp-minmax#depth");
    if (depth.min > 0) {
      query.minDepth(depth.min);
    }
    if (depth.max < 1e3) {
      query.maxDepth(depth.max);
    }
    return query;
  }
};
customElements.define("sp-earthquake-search", EarthquakeSearch);

// src/fdsnstationcomponent.mts
var fdsnstationcomponent_exports = {};
__export(fdsnstationcomponent_exports, {
  CHANNEL_SEARCH_ELEMENT: () => CHANNEL_SEARCH_ELEMENT,
  ChannelSearch: () => ChannelSearch
});
var channelsearchHtml = `
<div class="wrapper">
  <sp-channel-code-input></sp-channel-code-input>
  <div>
    <label>Time Range </label>
    <sp-timerange duration="P1Y" prev-next=true ></sp-timerange>
    <div>
    <button id="today">Today</button>
    <button id="week">Week</button>
    <button id="month">Month</button>
    <button id="year">Year</button>
  </div>
  <div>
    <label>Geo:</label>
    <sp-latlon-choice></sp-latlon-choice>
  </div>
</div>
`;
var ChannelSearch = class extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: "open" });
    this.draw_element(shadow);
  }
  _registerEvent(wrapper, sel) {
    const component = wrapper.querySelector(sel);
    if (!component) {
      throw new Error(`can't find ${sel}`);
    }
    component.addEventListener(
      "change",
      () => this.dispatchEvent(new Event("change"))
    );
  }
  draw_element(shadow) {
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    wrapper.innerHTML = channelsearchHtml;
    shadow.appendChild(wrapper);
    this._registerEvent(wrapper, "sp-timerange");
    this._registerEvent(wrapper, "sp-latlon-choice");
    const chanCodeEl = shadow.querySelector(
      "sp-channel-code-input"
    );
    if (chanCodeEl) {
      if (this.hasAttribute("network")) {
        const v = this.getAttribute("network");
        if (v) {
          chanCodeEl.network = v;
        }
      }
      if (this.hasAttribute("station")) {
        const v = this.getAttribute("station");
        if (v) {
          chanCodeEl.station = v;
        }
      }
      if (this.hasAttribute("location")) {
        const v = this.getAttribute("location");
        if (v) {
          chanCodeEl.location = v;
        }
      }
      if (this.hasAttribute("channel")) {
        const v = this.getAttribute("channel");
        if (v) {
          chanCodeEl.channel = v;
        }
      }
    }
    const trChooser = wrapper.querySelector("sp-timerange");
    if (!trChooser) {
      throw new Error("can't find sp-timerange");
    }
    if (this.hasAttribute("start")) {
      const s2 = this.getAttribute("start");
      if (s2 !== null) {
        trChooser.start = isoToDateTime(s2);
      }
    }
    if (this.hasAttribute("end")) {
      const e = this.getAttribute("end");
      if (e !== null) {
        trChooser.end = isoToDateTime(e);
      }
    }
    if (this.hasAttribute("duration")) {
      const d = this.getAttribute("duration");
      if (d !== null) {
        trChooser.duration = Duration.fromISO("" + d);
      }
    }
    const todayBtn = wrapper.querySelector("#today");
    if (!todayBtn) {
      throw new Error("can't find button#today");
    }
    todayBtn.addEventListener("click", (_event) => {
      trChooser.duration = Duration.fromISO("P1D");
    });
    const weekBtn = wrapper.querySelector("#week");
    if (!weekBtn) {
      throw new Error("can't find button#week");
    }
    weekBtn.addEventListener("click", (_event) => {
      trChooser.duration = Duration.fromISO("P7D");
    });
    const monthBtn = wrapper.querySelector("#month");
    if (!monthBtn) {
      throw new Error("can't find button#month");
    }
    monthBtn.addEventListener("click", (_event) => {
      trChooser.duration = Duration.fromISO("P1M");
    });
    const yearBtn = wrapper.querySelector("#year");
    if (!yearBtn) {
      throw new Error("can't find button#year");
    }
    yearBtn.addEventListener("click", (_event) => {
      trChooser.duration = Duration.fromISO("P1Y");
    });
    const latlonChooser = wrapper.querySelector(
      "sp-latlon-choice"
    );
    if (!latlonChooser) {
      throw new Error("can't find sp-latlon-choice");
    }
    LatLonChoice.observedAttributes.forEach((attr) => {
      if (this.hasAttribute(attr)) {
        const attrVal = this.getAttribute(attr);
        if (attrVal) {
          latlonChooser.setAttribute(attr, attrVal);
        }
      }
    });
  }
  populateQuery(query) {
    if (!query) {
      query = new StationQuery();
    }
    const wrapper = this.shadowRoot?.querySelector("div");
    const codeChooser = wrapper.querySelector(
      CHANNEL_CODE_ELEMENT
    );
    query.networkCode(codeChooser.network);
    query.stationCode(codeChooser.station);
    query.locationCode(codeChooser.location);
    query.channelCode(codeChooser.channel);
    const trChooser = wrapper.querySelector("sp-timerange");
    if (!trChooser) {
      throw new Error("can't find sp-timerange");
    }
    query.startTime(trChooser.start);
    query.endTime(trChooser.end);
    const latlonchoice = wrapper.querySelector(
      "sp-latlon-choice"
    );
    const choosenLatLon = latlonchoice.choosen();
    if (choosenLatLon instanceof LatLonBoxEl) {
      const latlonbox = choosenLatLon.asLatLonBox();
      if (latlonbox.south > -90) {
        query.minLat(latlonbox.south);
      }
      if (latlonbox.north < 90) {
        query.maxLat(latlonbox.north);
      }
      if (latlonbox.west > -180 && latlonbox.west + 360 !== latlonbox.east) {
        query.minLon(latlonbox.west);
      }
      if (latlonbox.east < 360 && latlonbox.west + 360 !== latlonbox.east) {
        query.maxLon(latlonbox.east);
      }
    } else if (choosenLatLon instanceof LatLonRadiusEl) {
      const latlonrad = choosenLatLon;
      if (latlonrad.minRadius > 0 || latlonrad.maxRadius < 180) {
        query.latitude(latlonrad.latitude);
        query.longitude(latlonrad.longitude);
        if (latlonrad.minRadius > 0) {
          query.minRadius(latlonrad.minRadius);
        }
        if (latlonrad.maxRadius < 180) {
          query.maxRadius(latlonrad.maxRadius);
        }
      }
    } else {
    }
    return query;
  }
  getGeoChoiceElement() {
    const wrapper = this.shadowRoot?.querySelector("div");
    const latlonchoice = wrapper.querySelector(
      "sp-latlon-choice"
    );
    return latlonchoice;
  }
};
var CHANNEL_SEARCH_ELEMENT = "sp-channel-search";
customElements.define(CHANNEL_SEARCH_ELEMENT, ChannelSearch);

// src/helicorder.mts
var helicorder_exports = {};
__export(helicorder_exports, {
  DEFAULT_MAX_HEIGHT: () => DEFAULT_MAX_HEIGHT,
  HELICORDER_ELEMENT: () => HELICORDER_ELEMENT,
  HELICORDER_SELECTOR: () => HELICORDER_SELECTOR,
  HELI_CLICK_EVENT: () => HELI_CLICK_EVENT,
  HELI_COLOR_CSS_ID: () => HELI_COLOR_CSS_ID,
  HELI_MOUSE_MOVE_EVENT: () => HELI_MOUSE_MOVE_EVENT,
  HeliTimeRange: () => HeliTimeRange,
  Helicorder: () => Helicorder,
  HelicorderConfig: () => HelicorderConfig,
  createNowHelicorderInterval: () => createNowHelicorderInterval,
  getNowLineEndTime: () => getNowLineEndTime,
  helicorder_css: () => helicorder_css
});
var HELI_CLICK_EVENT = "heliclick";
var HELI_MOUSE_MOVE_EVENT = "helimousemove";
var HELICORDER_ELEMENT = "sp-helicorder";
function getNowLineEndTime(hoursPerLine) {
  if (!hoursPerLine) {
    hoursPerLine = 2;
  }
  const e = DateTime.utc().endOf("hour").plus({ milliseconds: 1 });
  return e.plus({ hours: e.hour % hoursPerLine });
}
function createNowHelicorderInterval(hours, hoursPerLine) {
  const endTime = getNowLineEndTime(hoursPerLine);
  if (!hours) {
    hours = 24;
  }
  return Interval.before(
    endTime,
    Duration.fromObject({ hours })
  );
}
var Helicorder = class extends SeisPlotElement {
  constructor(seisData, seisConfig) {
    let heliConfig;
    if (!seisConfig) {
      const timeWindow = createNowHelicorderInterval();
      heliConfig = new HelicorderConfig(timeWindow);
    } else if (seisConfig instanceof HelicorderConfig) {
      heliConfig = seisConfig;
    } else {
      heliConfig = HelicorderConfig.fromSeismographConfig(seisConfig);
    }
    super(seisData, heliConfig);
    if (seisData && seisData.length > 1) {
      throw new Error(
        `Helicorder seisData must be length 1, but was ${seisData.length}`
      );
    }
    const wrapper = document.createElement("div");
    wrapper.setAttribute("class", "wrapper");
    this.addStyle(helicorder_css);
    this.getShadowRoot().appendChild(wrapper);
    this.addEventListener("click", (evt) => {
      const detail = this.calcDetailForEvent(evt);
      const event = new CustomEvent(
        HELI_CLICK_EVENT,
        {
          detail,
          bubbles: true,
          cancelable: false,
          composed: true
        }
      );
      this.dispatchEvent(event);
    });
    this.addEventListener("mousemove", (evt) => {
      const detail = this.calcDetailForEvent(evt);
      const event = new CustomEvent(
        HELI_MOUSE_MOVE_EVENT,
        {
          detail,
          bubbles: true,
          cancelable: false,
          composed: true
        }
      );
      this.dispatchEvent(event);
    });
    this.addEventListener(HELI_MOUSE_MOVE_EVENT, (hEvent) => {
      const detail = hEvent.detail;
      wrapper.querySelectorAll(`sp-seismograph`).forEach((seismograph, idx) => {
        if (idx === detail.lineNum) {
          let selectedStyle = seismograph.shadowRoot?.querySelector("style.selection");
          if (!selectedStyle) {
            selectedStyle = document.createElement("style");
            seismograph.shadowRoot?.insertBefore(
              selectedStyle,
              seismograph.shadowRoot?.firstChild
            );
            selectedStyle.setAttribute("class", "selection");
            selectedStyle.textContent = `
              svg g.yLabel text {
                font-weight: bold;
                text-decoration: underline;
              }
            `;
          }
        } else {
          seismograph.shadowRoot?.querySelector("style.selection")?.remove();
        }
      });
    });
  }
  get heliConfig() {
    return this.seismographConfig;
  }
  set heliConfig(config2) {
    const seismographList = this.shadowRoot ? Array.from(this.shadowRoot.querySelectorAll("sp-seismograph")) : [];
    const oldLinkedAmp = this.heliConfig.lineSeisConfig.linkedAmplitudeScale;
    if (oldLinkedAmp) {
      seismographList.forEach((e) => {
        oldLinkedAmp.unlink(e.amp_scalable);
      });
    }
    const newLinkedAmp = config2.lineSeisConfig.linkedAmplitudeScale;
    if (newLinkedAmp) {
      seismographList.forEach((e) => {
        newLinkedAmp.link(e.amp_scalable);
      });
    }
    this.seismographConfig = config2;
  }
  get width() {
    const wrapper = this.getShadowRoot().querySelector(
      "div.wrapper"
    );
    const rect = wrapper.getBoundingClientRect();
    return rect.width;
  }
  get height() {
    const wrapper = this.getShadowRoot().querySelector(
      "div.wrapper"
    );
    const rect = wrapper.getBoundingClientRect();
    return rect.height;
  }
  appendSegment(segment) {
    const segMinMax = segment.findMinMax();
    const origMinMax = this.heliConfig.fixedAmplitudeScale;
    const heliTimeRange = this.heliConfig.fixedTimeScale;
    if (!heliTimeRange) {
      throw new Error("Heli is not fixedTimeScale");
    }
    if (validEndTime(heliTimeRange) < validEndTime(segment.timeRange)) {
      const lineDuration = Duration.fromMillis(
        heliTimeRange.toDuration().toMillis() / this.heliConfig.numLines
      );
      this.heliConfig.fixedTimeScale = Interval.fromDateTimes(
        validStartTime(heliTimeRange).plus(lineDuration),
        validEndTime(heliTimeRange).plus(lineDuration)
      );
      this.redraw();
    }
    if (this.seisData && this.seisData.length > 0) {
      const singleSeisData = this.seisData[0];
      singleSeisData.append(segment);
      if (validEndTime(heliTimeRange) < validEndTime(segment.timeRange) || origMinMax && (segMinMax.min < origMinMax[0] || origMinMax[1] < segMinMax.max) || this.heliConfig.linkedAmplitudeScale) {
        this.configureAmplitudeFromData(singleSeisData);
        this.redraw();
      } else {
        const seismographList = this.shadowRoot ? Array.from(this.shadowRoot.querySelectorAll("sp-seismograph")) : [];
        seismographList.forEach((seisGraph) => {
          const lineInterval = seisGraph.displayTimeRangeForSeisDisplayData(singleSeisData);
          if (segment.timeRange.intersection(lineInterval)) {
            const lineSeisData = this.cutForLine(singleSeisData, lineInterval);
            seisGraph.seisData = [lineSeisData];
          }
        });
      }
    } else {
      const sdd = SeismogramDisplayData.fromSeismogram(new Seismogram(segment));
      this.seisData = [sdd];
    }
  }
  /**
   * draws the helicorder.
   */
  draw() {
    this.heliConfig.lineSeisConfig.amplitudeMode = this.heliConfig.amplitudeMode;
    this.drawSeismograms();
  }
  /**
   * draws or redraws the seismograms in the helicorder
   *
   * @private
   */
  drawSeismograms() {
    if (!this.isConnected) {
      return;
    }
    const wrapper = this.getShadowRoot().querySelector("div");
    const timeRange = this.heliConfig.fixedTimeScale;
    if (!isDef(timeRange)) {
      throw new Error("Helicorder config must have fixedTimeScale set");
    }
    this.configureAmplitudeFromData();
    let singleSeisData;
    if (this.seisData.length !== 0) {
      singleSeisData = this.seisData[0];
    } else {
      singleSeisData = new SeismogramDisplayData(timeRange);
    }
    const startTime = validStartTime(timeRange);
    const secondsPerLine = timeRange.toDuration().toMillis() / 1e3 / this.heliConfig.numLines;
    const seismographList = this.shadowRoot ? Array.from(this.shadowRoot.querySelectorAll("sp-seismograph")) : [];
    const lineTimes = this.calcTimesForLines(
      startTime,
      secondsPerLine,
      this.heliConfig.numLines
    );
    const margin = this.heliConfig.margin;
    const nl = this.heliConfig.numLines;
    const maxHeight = this.heliConfig.maxHeight !== null ? this.heliConfig.maxHeight : DEFAULT_MAX_HEIGHT;
    const baseHeight = (maxHeight - margin.top - margin.bottom) / (nl - (nl - 1) * this.heliConfig.overlap);
    const [timeLabelSpacing, timeLabelOffset] = anplusb(this.heliConfig.timeLabelSpacing);
    for (const lineTime of lineTimes) {
      const lineNumber = lineTime.lineNumber;
      const lineInterval = lineTime.interval;
      const startTime2 = lineTime.interval.start;
      const endTime = lineTime.interval.end;
      let height = baseHeight;
      const marginTop = lineNumber === 0 ? 0 : Math.round(-1 * height * this.heliConfig.overlap);
      const lineSeisConfig = this.heliConfig.lineSeisConfig.clone();
      lineSeisConfig.showTitle = false;
      if (lineNumber === 0) {
        lineSeisConfig.showTitle = true;
        lineSeisConfig.title = this.heliConfig.title;
        lineSeisConfig.isXAxisTop = this.heliConfig.isXAxisTop;
        lineSeisConfig.margin.top += this.heliConfig.margin.top;
        height += this.heliConfig.margin.top;
      } else if (lineNumber === nl - 1) {
        lineSeisConfig.isXAxis = this.heliConfig.isXAxis;
        lineSeisConfig.margin.bottom += this.heliConfig.margin.bottom;
        lineSeisConfig.xLabel = this.heliConfig.xLabel;
        lineSeisConfig.xSublabel = this.heliConfig.xSublabel;
        height += this.heliConfig.margin.bottom;
      }
      lineSeisConfig.xAxisTimeZone = this.heliConfig.xAxisTimeZone;
      lineSeisConfig.fixedTimeScale = lineInterval;
      const yLabelStep = (lineNumber - timeLabelOffset) / timeLabelSpacing;
      const doYLabels = Number.isInteger(yLabelStep) && yLabelStep >= 0 && yLabelStep < nl;
      if (doYLabels) {
        lineSeisConfig.yLabel = `${startTime2?.setZone(this.heliConfig.yLabelTimeZone).toFormat("HH:mm")}`;
        lineSeisConfig.yLabelRight = `${endTime?.setZone(this.heliConfig.yLabelRightTimeZone).toFormat("HH:mm")}`;
      }
      lineSeisConfig.lineColors = [
        this.heliConfig.lineColors[lineNumber % this.heliConfig.lineColors.length]
      ];
      const lineSeisData = this.cutForLine(singleSeisData, lineInterval);
      if (this.heliConfig.fixedAmplitudeScale && (this.heliConfig.fixedAmplitudeScale[0] !== 0 || this.heliConfig.fixedAmplitudeScale[1] !== 0)) {
        lineSeisConfig.fixedAmplitudeScale = this.heliConfig.fixedAmplitudeScale;
      }
      let seismograph;
      if (seismographList.length > lineNumber) {
        seismograph = seismographList[lineNumber];
        seismograph.setSeisDataAndConfig([lineSeisData], lineSeisConfig);
        if (lineSeisConfig.linkedAmplitudeScale) {
          lineSeisConfig.linkedAmplitudeScale.link(seismograph);
        }
      } else {
        seismograph = new Seismograph([lineSeisData], lineSeisConfig);
        wrapper.appendChild(seismograph);
      }
      seismograph.svg.classed(HELICORDER_SELECTOR, true);
      seismograph.setAttribute("class", "heliLine");
      seismograph.setAttribute(
        "style",
        `height: ${height}px;margin-top: ${marginTop}px`
      );
      const seismographWrapper = seismograph.shadowRoot?.querySelector(
        "div"
      );
      const styleEl = document.createElement("style");
      styleEl.classList.add("helistyle");
      const seismographRoot = seismograph.shadowRoot;
      if (seismographRoot && seismographRoot.querySelector("style.helistyle") == null) {
        const helicss = seismographRoot.insertBefore(
          styleEl,
          seismographWrapper
        );
        helicss.textContent = `
        .yLabel text {
          font-size: x-small;
          fill: ${lineSeisConfig.lineColors[0]};
        }
        .utclabels {
          position: relative;
          font-size: x-small;
          width: 100%;
        }
        .utclabels div {
          display: flex;
          position: absolute;
          left: 0px;
          justify-content: space-between;
          width: 100%;
          z-index: -1;
        }
        `;
      }
      if (lineNumber === 0) {
        let utcDiv = seismographWrapper.querySelector("div.utclabels");
        if (utcDiv != null) {
          seismographWrapper.removeChild(utcDiv);
        }
        utcDiv = document.createElement("div");
        utcDiv.setAttribute("class", "utclabels");
        const innerDiv = utcDiv.appendChild(document.createElement("div"));
        innerDiv.setAttribute("style", `top: ${lineSeisConfig.margin.top}px;`);
        const textEl = innerDiv.appendChild(document.createElement("text"));
        textEl.textContent = nameForTimeZone(this.heliConfig.yLabelTimeZone, startTime2);
        const rightTextEl = innerDiv.appendChild(document.createElement("text"));
        rightTextEl.textContent = nameForTimeZone(this.heliConfig.yLabelRightTimeZone, startTime2);
        seismographWrapper.insertBefore(utcDiv, seismographWrapper.firstChild);
      }
      if (this.heliConfig.lineSeisConfig.linkedAmplitudeScale) {
        this.heliConfig.lineSeisConfig.linkedAmplitudeScale.recalculate().catch((e) => warn(e));
      } else {
        seismograph.redraw();
      }
    }
  }
  configureAmplitudeFromData(singleSeisData) {
    const timeRange = this.heliConfig.fixedTimeScale;
    if (!isDef(timeRange)) {
      throw new Error("Helicorder config must have fixedTimeScale set");
    }
    let maxVariation = 1;
    if (singleSeisData == null) {
      if (this.seisData.length !== 0) {
        singleSeisData = this.seisData[0];
      } else {
        singleSeisData = new SeismogramDisplayData(timeRange);
      }
    }
    if (singleSeisData.seismogram) {
      const mul_percent = 1.01;
      if (!this.heliConfig.fixedAmplitudeScale || this.heliConfig.fixedAmplitudeScale[0] === 0 && this.heliConfig.fixedAmplitudeScale[1] === 0) {
        if (this.heliConfig.maxVariation === 0) {
          if (singleSeisData.seismogram.timeRange.overlaps(timeRange)) {
            const minMax = findMinMaxOverTimeRange(
              [singleSeisData],
              timeRange,
              false,
              this.heliConfig.amplitudeMode
            );
            maxVariation = minMax.expandPercentage(mul_percent).fullWidth;
          }
        } else {
          maxVariation = this.heliConfig.maxVariation;
        }
        if (this.heliConfig.lineSeisConfig.linkedAmplitudeScale) {
          this.heliConfig.lineSeisConfig.linkedAmplitudeScale.halfWidth = maxVariation;
        }
      }
    }
  }
  cutForLine(singleSeisData, lineInterval) {
    let lineCutSeis;
    let lineSeisData;
    if (singleSeisData.seismogram) {
      lineCutSeis = singleSeisData.seismogram.cut(lineInterval);
      if (lineCutSeis && this.heliConfig.detrendLines) {
        lineCutSeis = removeTrend(lineCutSeis);
      }
      lineSeisData = singleSeisData.cloneWithNewSeismogram(lineCutSeis);
    } else {
      lineSeisData = singleSeisData.clone();
    }
    lineSeisData.timeRange = lineInterval;
    return lineSeisData;
  }
  /**
   * Calculates the time range covered by each line of the display
   *
   * @param   startTime      start of display
   * @param   secondsPerLine seconds covered by each line
   * @param   numberOfLines  number of lines
   * @returns Array of HeliTimeRange, one per line
   */
  calcTimesForLines(startTime, secondsPerLine, numberOfLines) {
    const out = [];
    let s2 = startTime;
    const durationPerLine = Duration.fromMillis(secondsPerLine * 1e3);
    for (let lineNum = 0; lineNum < numberOfLines; lineNum++) {
      const startEnd2 = new HeliTimeRange(s2, durationPerLine, lineNum);
      out.push(startEnd2);
      s2 = validEndTime(startEnd2.interval);
    }
    return out;
  }
  calcDetailForEvent(evt) {
    if (!(evt instanceof MouseEvent)) {
      throw new Error("expect mouse event but not instanceof");
    }
    const heliMargin = this.heliConfig.margin;
    const margin = this.heliConfig.lineSeisConfig.margin;
    const nl = this.heliConfig.numLines;
    const maxHeight = this.heliConfig.maxHeight !== null ? this.heliConfig.maxHeight : DEFAULT_MAX_HEIGHT;
    const baseHeight = (maxHeight - (heliMargin.top + heliMargin.bottom)) / (nl - (nl - 1) * this.heliConfig.overlap);
    let clickLine;
    if (evt.offsetY < heliMargin.top + baseHeight * 0.5) {
      clickLine = 0;
    } else {
      clickLine = Math.round(
        (evt.offsetY - heliMargin.top - baseHeight * 0.5) / (baseHeight * (1 - this.heliConfig.overlap))
      );
    }
    const timeRange = this.heliConfig.fixedTimeScale;
    if (timeRange) {
      const timeLineFraction = (evt.offsetX - margin.left) / (this.width - margin.left - margin.right);
      const secondsPerLine = timeRange.toDuration().toMillis() / 1e3 / this.heliConfig.numLines;
      const clickTime = validStartTime(timeRange).plus(
        Duration.fromMillis(
          (clickLine + timeLineFraction) * secondsPerLine * 1e3
        )
      );
      let channel = null;
      if (this.seisData.length > 0) {
        channel = this.seisData[0].channel;
      }
      return {
        mouseevent: evt,
        time: clickTime,
        lineNum: clickLine,
        channel
      };
    } else {
      throw new Error("Helicorder must be fixedTimeScale");
    }
  }
};
var DEFAULT_MAX_HEIGHT = 600;
var HelicorderConfig = class _HelicorderConfig extends SeismographConfig {
  constructor(timeRange, lineSeisConfig) {
    super();
    this.detrendLines = false;
    this.yLabelTimeZone = FixedOffsetZone.utcInstance;
    this.yLabelRightTimeZone = FixedOffsetZone.utcInstance;
    if (!isDef(timeRange)) {
      throw new Error("Helicorder config must have fixedTimeScale set");
    }
    this.fixedTimeScale = timeRange;
    this.maxVariation = 0;
    this.maxHeight = DEFAULT_MAX_HEIGHT;
    this.xLabel = "";
    this.yLabel = "";
    this.xSublabel = "";
    this.ySublabel = " ";
    this.ySublabelIsUnits = false;
    this.isXAxis = true;
    this.isXAxisTop = true;
    this.isYAxis = false;
    this.overlap = 0.5;
    this.numLines = 12;
    this.margin.left = 0;
    this.margin.right = 0;
    this.margin.top = 40;
    this.timeLabelSpacing = 1;
    this.lineColors = ["skyblue", "olivedrab", "goldenrod"];
    if (lineSeisConfig == null) {
      lineSeisConfig = new SeismographConfig();
      lineSeisConfig.amplitudeMode = "minmax" /* MinMax */;
      lineSeisConfig.linkedAmplitudeScale = new FixedHalfWidthAmplitudeScale(
        1
      );
      lineSeisConfig.ySublabel = ` `;
      lineSeisConfig.xLabel = " ";
      lineSeisConfig.yLabel = "";
      lineSeisConfig.yLabelOrientation = "horizontal";
      lineSeisConfig.ySublabelIsUnits = false;
      lineSeisConfig.isXAxis = false;
      lineSeisConfig.isYAxis = false;
      lineSeisConfig.minHeight = 80;
      lineSeisConfig.margin.top = 0;
      lineSeisConfig.margin.bottom = 0;
      lineSeisConfig.margin.left = 37;
      lineSeisConfig.margin.right = 37;
      lineSeisConfig.wheelZoom = false;
    }
    this.lineSeisConfig = lineSeisConfig;
  }
  static fromSeismographConfig(seisConfig) {
    if (!seisConfig.fixedTimeScale) {
      throw new Error("Helicorder config must have fixedTimeScale set");
    }
    const heliConfig = new _HelicorderConfig(seisConfig.fixedTimeScale, seisConfig);
    heliConfig.lineColors = seisConfig.lineColors;
    return heliConfig;
  }
};
var HeliTimeRange = class {
  constructor(startTime, duration3, lineNumber) {
    this.interval = startDuration(startTime, duration3);
    this.lineNumber = lineNumber;
  }
};
var helicorder_css = `
:host {
  display: block;
  min-height: 200px;
  height: 100%;
  cursor: crosshair;
}
`;
var HELICORDER_SELECTOR = "helicorder";
var HELI_COLOR_CSS_ID = "helicordercolors";
customElements.define(HELICORDER_ELEMENT, Helicorder);

// src/mseedarchive.mts
var mseedarchive_exports = {};
__export(mseedarchive_exports, {
  Allowed_Flags: () => Allowed_Flags,
  MSeedArchive: () => MSeedArchive,
  loadDataRecords: () => loadDataRecords,
  maxSampleRate: () => maxSampleRate,
  maxTimeForRecord: () => maxTimeForRecord,
  minSampleRate: () => minSampleRate
});
var Allowed_Flags = ["n", "s", "l", "c", "Y", "j", "H"];
var MSeedArchive = class {
  constructor(rootUrl, pattern) {
    this._rootUrl = fixProtocolInUrl(rootUrl);
    this._pattern = pattern;
    this._recordSize = 512;
    this._timeoutSec = 30;
    this.checkPattern(this._pattern);
  }
  get rootUrl() {
    return this._rootUrl;
  }
  get pattern() {
    return this._pattern;
  }
  get recordSize() {
    return this._recordSize;
  }
  /**
   * checks pattern for allowed flags as not all that are supported
   * by ringserver are supported here. Must only include:
   * * n network code, white space removed
   * * s station code, white space removed
   * * l  location code, white space removed
   * * c  channel code, white space removed
   * * Y  year, 4 digits
   * * j  day of year, 3 digits zero padded
   * * H  hour, 2 digits zero padded
   *
   * @param p mseed archive pattern string
   * @returns true if all flags are allowed
   */
  checkPattern(p) {
    const regexp = /%[a-zA-Z]/g;
    const allFlags = p.match(regexp);
    if (!allFlags) {
      return false;
    } else {
      for (const f of allFlags) {
        if (Allowed_Flags.indexOf(f.slice(1)) === -1) {
          throw new Error(`${f} not allowed in pattern`);
        }
      }
    }
    return true;
  }
  /**
   * Loads seismograms from the remote miniseed archive via
   * http(s). Files downloaded include all that might overlap
   * the given time window based on record size,
   * the minimum sample rate
   * for the channel band code and the given time window.
   *
   * @param   channelTimeList request channels and time windows
   * @returns Promise to the same SeismogramDisplayData array, but with seismograms populated
   */
  loadSeismograms(channelTimeList) {
    const promiseArray = channelTimeList.map((ct) => {
      if (isDef(ct.channel)) {
        const request = Promise.resolve(ct);
        const dataRecords = this.loadDataForChannel(
          ct.channel,
          ct.startTime,
          ct.endTime
        );
        return Promise.all([request, dataRecords]).then((pArray) => {
          return {
            request: pArray[0],
            dataRecords: pArray[1]
          };
        });
      } else if (isDef(ct.sourceId)) {
        const request = Promise.resolve(ct);
        const dataRecords = this.loadData(
          ct.sourceId.networkCode,
          ct.sourceId.stationCode,
          ct.sourceId.locationCode,
          ct.sourceId.formChannelCode(),
          ct.startTime,
          ct.endTime
        );
        return Promise.all([request, dataRecords]).then((pArray) => {
          return {
            request: pArray[0],
            dataRecords: pArray[1]
          };
        });
      } else {
        throw new Error("channel is missing in loadSeismograms ");
      }
    });
    return Promise.all(promiseArray).then((pArray) => {
      const out = [];
      pArray.forEach((p) => {
        const seisArray = seismogramPerChannel(p.dataRecords);
        for (const seis of seisArray) {
          const cutSeis = seis.cut(
            Interval.fromDateTimes(p.request.startTime, p.request.endTime)
          );
          p.request.seismogram = cutSeis;
          out.push(p.request);
        }
      });
      return out;
    });
  }
  /**
   * Loads miniseed records based on channel and time window.
   *
   * @param   channel   channel to request
   * @param   startTime start time
   * @param   endTime   end time
   * @returns Promise to array of miniseed records
   */
  loadDataForChannel(channel, startTime, endTime) {
    return this.loadData(
      channel.station.network.networkCode,
      channel.station.stationCode,
      channel.locationCode,
      channel.channelCode,
      startTime,
      endTime,
      channel.sampleRate
    );
  }
  /**
   * Loads miniseed records based on string channel codes.
   *
   * @param   net        network code
   * @param   sta        station code
   * @param   loc        location code
   * @param   chan       channel code
   * @param   startTime  start time
   * @param   endTime    end time
   * @param   sampleRate known sample rate for this channel
   * @returns             Promise to array of miniseed records
   */
  loadData(net, sta, loc, chan, startTime, endTime, sampleRate) {
    const basePattern = this.fillBasePattern(net, sta, loc, chan);
    if (!isDef(sampleRate)) {
      sampleRate = minSampleRate(chan);
    }
    const recordTime = maxTimeForRecord(this._recordSize, sampleRate);
    let t = startTime.minus(recordTime);
    const urlList = [];
    while (t < endTime) {
      const url2 = appendToPath(this.rootUrl, this.fillTimePattern(basePattern, t));
      t = t.plus(Duration.fromObject({ hour: 1 }));
      urlList.push(url2);
    }
    if (t.plus(recordTime) > endTime) {
      const url2 = appendToPath(this.rootUrl, this.fillTimePattern(basePattern, t));
      urlList.push(url2);
    }
    return loadDataRecords(urlList).then((dataRecords) => {
      if (dataRecords) {
        dataRecords = dataRecords.filter(
          (dr) => dr.header.endTime >= startTime && dr.header.startTime <= endTime
        );
      } else {
        dataRecords = [];
      }
      return dataRecords;
    });
  }
  /**
   * Replaces codes from channel in base pattern.
   *
   * @param   net  string to replace '%n'
   * @param   sta  string to replace '%s'
   * @param   loc  string to replace '%l'
   * @param   chan string to replace '%c'
   * @returns       new string with channel replacements made
   */
  fillBasePattern(net, sta, loc, chan) {
    return this.pattern.replace(/%n/g, net).replace(/%s/g, sta).replace(/%l/g, loc).replace(/%c/g, chan);
  }
  /**
   * Replaces time entries ( %Y, %j, %H ) in pattern.
   *
   * @param   basePattern pattern to replace in
   * @param   t           DateTime in time
   * @returns              string with time replaces
   */
  fillTimePattern(basePattern, t) {
    return basePattern.replace(/%Y/g, t.toFormat("yyyy")).replace(/%j/g, t.toFormat("ooo")).replace(/%H/g, t.toFormat("HH"));
  }
};
function loadDataRecords(urlList, fetchInit, timeoutSec2) {
  const promiseArray = urlList.map((url2) => {
    return doFetchWithTimeout(url2, fetchInit, timeoutSec2).then((fetchResponse) => {
      if (fetchResponse.ok) {
        if (fetchResponse.status === 200 || fetchResponse.status === 304) {
          return fetchResponse.arrayBuffer().then((ab) => {
            let dataRecords = [];
            if (ab.byteLength > 0) {
              dataRecords = parseDataRecords(ab);
            }
            return dataRecords;
          });
        } else if (fetchResponse.status === 404) {
          return [];
        } else {
          log(
            "no data: status=" + fetchResponse.status + " " + fetchResponse.url
          );
          return [];
        }
      } else if (fetchResponse.status === 404) {
        return [];
      } else {
        throw new Error(
          "fetch error: " + fetchResponse.ok + " " + fetchResponse.status + " " + fetchResponse.url
        );
      }
    }).catch((err) => {
      log("caught fetch err, continuing with empty: " + String(err));
      return [];
    });
  });
  return Promise.all(promiseArray).then((pArray) => {
    let dataRecords = [];
    pArray.forEach((p) => {
      dataRecords = dataRecords.concat(p);
    });
    return dataRecords;
  });
}
function maxSampleRate(chan) {
  const f = chan.slice(0, 1);
  switch (f) {
    case "F":
    case "G":
      return 5e3;
    case "D":
    case "C":
      return 1e3;
    case "E":
    case "H":
      return 250;
    case "S":
    case "B":
      return 80;
    case "M":
      return 10;
    case "L":
      return 1;
    case "V":
      return 0.1;
    case "U":
      return 0.01;
    case "R":
      return 1e-3;
    case "P":
      return 1e-4;
    case "Q":
      return 1e-6;
    default:
      throw new Error("Unknown band code " + f + " in " + chan);
  }
}
function minSampleRate(chan) {
  const f = chan.slice(0, 1);
  switch (f) {
    case "F":
    case "G":
      return 1e3;
    case "D":
    case "C":
      return 2500;
    case "E":
    case "H":
      return 80;
    case "S":
    case "B":
      return 10;
    case "M":
      return 1;
    case "L":
      return 1;
    // maybe wrong, seed manual not clear
    case "V":
      return 0.1;
    // maybe wrong, seed manual not clear
    case "U":
      return 0.01;
    // maybe wrong, seed manual not clear
    case "R":
      return 1e-4;
    case "P":
      return 1e-5;
    case "Q":
      return 1e-7;
    default:
      throw new Error("Unknown band code " + f + " in " + chan);
  }
}
function maxTimeForRecord(recordSize, sampleRate) {
  return Duration.fromMillis(1e3 * ((recordSize - 40) * 2) / sampleRate);
}

// src/nws.mts
var nws_exports = {};
__export(nws_exports, {
  NWSBaseObj: () => NWSBaseObj,
  NWSForecast: () => NWSForecast,
  NWSForecastPeriod: () => NWSForecastPeriod,
  NWSObsMeasurement: () => NWSObsMeasurement,
  NWSObsStation: () => NWSObsStation,
  NWSObsStationCollection: () => NWSObsStationCollection,
  NWSObservation: () => NWSObservation,
  NWSPointInfo: () => NWSPointInfo,
  loadForecast: () => loadForecast,
  loadNWSPointInfo: () => loadNWSPointInfo,
  loadObservation: () => loadObservation,
  nwsObservation: () => nwsObservation
});

// node_modules/zod/v4/classic/external.js
var external_exports = {};
__export(external_exports, {
  $brand: () => $brand,
  $input: () => $input,
  $output: () => $output,
  NEVER: () => NEVER,
  TimePrecision: () => TimePrecision,
  ZodAny: () => ZodAny,
  ZodArray: () => ZodArray,
  ZodBase64: () => ZodBase64,
  ZodBase64URL: () => ZodBase64URL,
  ZodBigInt: () => ZodBigInt,
  ZodBigIntFormat: () => ZodBigIntFormat,
  ZodBoolean: () => ZodBoolean,
  ZodCIDRv4: () => ZodCIDRv4,
  ZodCIDRv6: () => ZodCIDRv6,
  ZodCUID: () => ZodCUID,
  ZodCUID2: () => ZodCUID2,
  ZodCatch: () => ZodCatch,
  ZodCodec: () => ZodCodec,
  ZodCustom: () => ZodCustom,
  ZodCustomStringFormat: () => ZodCustomStringFormat,
  ZodDate: () => ZodDate,
  ZodDefault: () => ZodDefault,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodE164: () => ZodE164,
  ZodEmail: () => ZodEmail,
  ZodEmoji: () => ZodEmoji,
  ZodEnum: () => ZodEnum,
  ZodError: () => ZodError,
  ZodExactOptional: () => ZodExactOptional,
  ZodFile: () => ZodFile,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  ZodFunction: () => ZodFunction,
  ZodGUID: () => ZodGUID,
  ZodIPv4: () => ZodIPv4,
  ZodIPv6: () => ZodIPv6,
  ZodISODate: () => ZodISODate,
  ZodISODateTime: () => ZodISODateTime,
  ZodISODuration: () => ZodISODuration,
  ZodISOTime: () => ZodISOTime,
  ZodIntersection: () => ZodIntersection,
  ZodIssueCode: () => ZodIssueCode,
  ZodJWT: () => ZodJWT,
  ZodKSUID: () => ZodKSUID,
  ZodLazy: () => ZodLazy,
  ZodLiteral: () => ZodLiteral,
  ZodMAC: () => ZodMAC,
  ZodMap: () => ZodMap,
  ZodNaN: () => ZodNaN,
  ZodNanoID: () => ZodNanoID,
  ZodNever: () => ZodNever,
  ZodNonOptional: () => ZodNonOptional,
  ZodNull: () => ZodNull,
  ZodNullable: () => ZodNullable,
  ZodNumber: () => ZodNumber,
  ZodNumberFormat: () => ZodNumberFormat,
  ZodObject: () => ZodObject,
  ZodOptional: () => ZodOptional,
  ZodPipe: () => ZodPipe,
  ZodPrefault: () => ZodPrefault,
  ZodPreprocess: () => ZodPreprocess,
  ZodPromise: () => ZodPromise,
  ZodReadonly: () => ZodReadonly,
  ZodRealError: () => ZodRealError,
  ZodRecord: () => ZodRecord,
  ZodSet: () => ZodSet,
  ZodString: () => ZodString,
  ZodStringFormat: () => ZodStringFormat,
  ZodSuccess: () => ZodSuccess,
  ZodSymbol: () => ZodSymbol,
  ZodTemplateLiteral: () => ZodTemplateLiteral,
  ZodTransform: () => ZodTransform,
  ZodTuple: () => ZodTuple,
  ZodType: () => ZodType,
  ZodULID: () => ZodULID,
  ZodURL: () => ZodURL,
  ZodUUID: () => ZodUUID,
  ZodUndefined: () => ZodUndefined,
  ZodUnion: () => ZodUnion,
  ZodUnknown: () => ZodUnknown,
  ZodVoid: () => ZodVoid,
  ZodXID: () => ZodXID,
  ZodXor: () => ZodXor,
  _ZodString: () => _ZodString,
  _default: () => _default2,
  _function: () => _function,
  any: () => any,
  array: () => array2,
  base64: () => base642,
  base64url: () => base64url2,
  bigint: () => bigint2,
  boolean: () => boolean2,
  catch: () => _catch2,
  check: () => check,
  cidrv4: () => cidrv42,
  cidrv6: () => cidrv62,
  clone: () => clone2,
  codec: () => codec,
  coerce: () => coerce_exports,
  config: () => config,
  core: () => core_exports2,
  cuid: () => cuid3,
  cuid2: () => cuid22,
  custom: () => custom,
  date: () => date4,
  decode: () => decode2,
  decodeAsync: () => decodeAsync2,
  describe: () => describe2,
  discriminatedUnion: () => discriminatedUnion,
  e164: () => e1642,
  email: () => email2,
  emoji: () => emoji2,
  encode: () => encode2,
  encodeAsync: () => encodeAsync2,
  endsWith: () => _endsWith,
  enum: () => _enum2,
  exactOptional: () => exactOptional,
  file: () => file,
  flattenError: () => flattenError,
  float32: () => float32,
  float64: () => float64,
  formatError: () => formatError,
  fromJSONSchema: () => fromJSONSchema,
  function: () => _function,
  getErrorMap: () => getErrorMap,
  globalRegistry: () => globalRegistry,
  gt: () => _gt,
  gte: () => _gte,
  guid: () => guid2,
  hash: () => hash,
  hex: () => hex3,
  hostname: () => hostname2,
  httpUrl: () => httpUrl,
  includes: () => _includes,
  instanceof: () => _instanceof,
  int: () => int2,
  int32: () => int32,
  int64: () => int64,
  intersection: () => intersection,
  invertCodec: () => invertCodec,
  ipv4: () => ipv42,
  ipv6: () => ipv62,
  iso: () => iso_exports,
  json: () => json,
  jwt: () => jwt,
  keyof: () => keyof,
  ksuid: () => ksuid2,
  lazy: () => lazy,
  length: () => _length,
  literal: () => literal,
  locales: () => locales_exports,
  looseObject: () => looseObject,
  looseRecord: () => looseRecord,
  lowercase: () => _lowercase,
  lt: () => _lt,
  lte: () => _lte,
  mac: () => mac2,
  map: () => map3,
  maxLength: () => _maxLength,
  maxSize: () => _maxSize,
  meta: () => meta2,
  mime: () => _mime,
  minLength: () => _minLength,
  minSize: () => _minSize,
  multipleOf: () => _multipleOf,
  nan: () => nan,
  nanoid: () => nanoid2,
  nativeEnum: () => nativeEnum,
  negative: () => _negative,
  never: () => never,
  nonnegative: () => _nonnegative,
  nonoptional: () => nonoptional,
  nonpositive: () => _nonpositive,
  normalize: () => _normalize,
  null: () => _null3,
  nullable: () => nullable,
  nullish: () => nullish2,
  number: () => number6,
  object: () => object,
  optional: () => optional,
  overwrite: () => _overwrite,
  parse: () => parse4,
  parseAsync: () => parseAsync2,
  partialRecord: () => partialRecord,
  pipe: () => pipe,
  positive: () => _positive,
  prefault: () => prefault,
  preprocess: () => preprocess,
  prettifyError: () => prettifyError,
  promise: () => promise,
  property: () => _property,
  readonly: () => readonly,
  record: () => record,
  refine: () => refine,
  regex: () => _regex,
  regexes: () => regexes_exports,
  registry: () => registry,
  safeDecode: () => safeDecode2,
  safeDecodeAsync: () => safeDecodeAsync2,
  safeEncode: () => safeEncode2,
  safeEncodeAsync: () => safeEncodeAsync2,
  safeParse: () => safeParse2,
  safeParseAsync: () => safeParseAsync2,
  set: () => set3,
  setErrorMap: () => setErrorMap,
  size: () => _size,
  slugify: () => _slugify,
  startsWith: () => _startsWith,
  strictObject: () => strictObject,
  string: () => string2,
  stringFormat: () => stringFormat,
  stringbool: () => stringbool,
  success: () => success,
  superRefine: () => superRefine,
  symbol: () => symbol,
  templateLiteral: () => templateLiteral,
  toJSONSchema: () => toJSONSchema,
  toLowerCase: () => _toLowerCase,
  toUpperCase: () => _toUpperCase,
  transform: () => transform,
  treeifyError: () => treeifyError,
  trim: () => _trim,
  tuple: () => tuple,
  uint32: () => uint32,
  uint64: () => uint64,
  ulid: () => ulid2,
  undefined: () => _undefined3,
  union: () => union,
  unknown: () => unknown,
  uppercase: () => _uppercase,
  url: () => url,
  util: () => util_exports2,
  uuid: () => uuid2,
  uuidv4: () => uuidv4,
  uuidv6: () => uuidv6,
  uuidv7: () => uuidv7,
  void: () => _void2,
  xid: () => xid2,
  xor: () => xor
});

// node_modules/zod/v4/core/index.js
var core_exports2 = {};
__export(core_exports2, {
  $ZodAny: () => $ZodAny,
  $ZodArray: () => $ZodArray,
  $ZodAsyncError: () => $ZodAsyncError,
  $ZodBase64: () => $ZodBase64,
  $ZodBase64URL: () => $ZodBase64URL,
  $ZodBigInt: () => $ZodBigInt,
  $ZodBigIntFormat: () => $ZodBigIntFormat,
  $ZodBoolean: () => $ZodBoolean,
  $ZodCIDRv4: () => $ZodCIDRv4,
  $ZodCIDRv6: () => $ZodCIDRv6,
  $ZodCUID: () => $ZodCUID,
  $ZodCUID2: () => $ZodCUID2,
  $ZodCatch: () => $ZodCatch,
  $ZodCheck: () => $ZodCheck,
  $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat,
  $ZodCheckEndsWith: () => $ZodCheckEndsWith,
  $ZodCheckGreaterThan: () => $ZodCheckGreaterThan,
  $ZodCheckIncludes: () => $ZodCheckIncludes,
  $ZodCheckLengthEquals: () => $ZodCheckLengthEquals,
  $ZodCheckLessThan: () => $ZodCheckLessThan,
  $ZodCheckLowerCase: () => $ZodCheckLowerCase,
  $ZodCheckMaxLength: () => $ZodCheckMaxLength,
  $ZodCheckMaxSize: () => $ZodCheckMaxSize,
  $ZodCheckMimeType: () => $ZodCheckMimeType,
  $ZodCheckMinLength: () => $ZodCheckMinLength,
  $ZodCheckMinSize: () => $ZodCheckMinSize,
  $ZodCheckMultipleOf: () => $ZodCheckMultipleOf,
  $ZodCheckNumberFormat: () => $ZodCheckNumberFormat,
  $ZodCheckOverwrite: () => $ZodCheckOverwrite,
  $ZodCheckProperty: () => $ZodCheckProperty,
  $ZodCheckRegex: () => $ZodCheckRegex,
  $ZodCheckSizeEquals: () => $ZodCheckSizeEquals,
  $ZodCheckStartsWith: () => $ZodCheckStartsWith,
  $ZodCheckStringFormat: () => $ZodCheckStringFormat,
  $ZodCheckUpperCase: () => $ZodCheckUpperCase,
  $ZodCodec: () => $ZodCodec,
  $ZodCustom: () => $ZodCustom,
  $ZodCustomStringFormat: () => $ZodCustomStringFormat,
  $ZodDate: () => $ZodDate,
  $ZodDefault: () => $ZodDefault,
  $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion,
  $ZodE164: () => $ZodE164,
  $ZodEmail: () => $ZodEmail,
  $ZodEmoji: () => $ZodEmoji,
  $ZodEncodeError: () => $ZodEncodeError,
  $ZodEnum: () => $ZodEnum,
  $ZodError: () => $ZodError,
  $ZodExactOptional: () => $ZodExactOptional,
  $ZodFile: () => $ZodFile,
  $ZodFunction: () => $ZodFunction,
  $ZodGUID: () => $ZodGUID,
  $ZodIPv4: () => $ZodIPv4,
  $ZodIPv6: () => $ZodIPv6,
  $ZodISODate: () => $ZodISODate,
  $ZodISODateTime: () => $ZodISODateTime,
  $ZodISODuration: () => $ZodISODuration,
  $ZodISOTime: () => $ZodISOTime,
  $ZodIntersection: () => $ZodIntersection,
  $ZodJWT: () => $ZodJWT,
  $ZodKSUID: () => $ZodKSUID,
  $ZodLazy: () => $ZodLazy,
  $ZodLiteral: () => $ZodLiteral,
  $ZodMAC: () => $ZodMAC,
  $ZodMap: () => $ZodMap,
  $ZodNaN: () => $ZodNaN,
  $ZodNanoID: () => $ZodNanoID,
  $ZodNever: () => $ZodNever,
  $ZodNonOptional: () => $ZodNonOptional,
  $ZodNull: () => $ZodNull,
  $ZodNullable: () => $ZodNullable,
  $ZodNumber: () => $ZodNumber,
  $ZodNumberFormat: () => $ZodNumberFormat,
  $ZodObject: () => $ZodObject,
  $ZodObjectJIT: () => $ZodObjectJIT,
  $ZodOptional: () => $ZodOptional,
  $ZodPipe: () => $ZodPipe,
  $ZodPrefault: () => $ZodPrefault,
  $ZodPreprocess: () => $ZodPreprocess,
  $ZodPromise: () => $ZodPromise,
  $ZodReadonly: () => $ZodReadonly,
  $ZodRealError: () => $ZodRealError,
  $ZodRecord: () => $ZodRecord,
  $ZodRegistry: () => $ZodRegistry,
  $ZodSet: () => $ZodSet,
  $ZodString: () => $ZodString,
  $ZodStringFormat: () => $ZodStringFormat,
  $ZodSuccess: () => $ZodSuccess,
  $ZodSymbol: () => $ZodSymbol,
  $ZodTemplateLiteral: () => $ZodTemplateLiteral,
  $ZodTransform: () => $ZodTransform,
  $ZodTuple: () => $ZodTuple,
  $ZodType: () => $ZodType,
  $ZodULID: () => $ZodULID,
  $ZodURL: () => $ZodURL,
  $ZodUUID: () => $ZodUUID,
  $ZodUndefined: () => $ZodUndefined,
  $ZodUnion: () => $ZodUnion,
  $ZodUnknown: () => $ZodUnknown,
  $ZodVoid: () => $ZodVoid,
  $ZodXID: () => $ZodXID,
  $ZodXor: () => $ZodXor,
  $brand: () => $brand,
  $constructor: () => $constructor,
  $input: () => $input,
  $output: () => $output,
  Doc: () => Doc,
  JSONSchema: () => json_schema_exports,
  JSONSchemaGenerator: () => JSONSchemaGenerator,
  NEVER: () => NEVER,
  TimePrecision: () => TimePrecision,
  _any: () => _any,
  _array: () => _array,
  _base64: () => _base64,
  _base64url: () => _base64url,
  _bigint: () => _bigint,
  _boolean: () => _boolean,
  _catch: () => _catch,
  _check: () => _check,
  _cidrv4: () => _cidrv4,
  _cidrv6: () => _cidrv6,
  _coercedBigint: () => _coercedBigint,
  _coercedBoolean: () => _coercedBoolean,
  _coercedDate: () => _coercedDate,
  _coercedNumber: () => _coercedNumber,
  _coercedString: () => _coercedString,
  _cuid: () => _cuid,
  _cuid2: () => _cuid2,
  _custom: () => _custom,
  _date: () => _date,
  _decode: () => _decode,
  _decodeAsync: () => _decodeAsync,
  _default: () => _default,
  _discriminatedUnion: () => _discriminatedUnion,
  _e164: () => _e164,
  _email: () => _email,
  _emoji: () => _emoji2,
  _encode: () => _encode,
  _encodeAsync: () => _encodeAsync,
  _endsWith: () => _endsWith,
  _enum: () => _enum,
  _file: () => _file,
  _float32: () => _float32,
  _float64: () => _float64,
  _gt: () => _gt,
  _gte: () => _gte,
  _guid: () => _guid,
  _includes: () => _includes,
  _int: () => _int,
  _int32: () => _int32,
  _int64: () => _int64,
  _intersection: () => _intersection,
  _ipv4: () => _ipv4,
  _ipv6: () => _ipv6,
  _isoDate: () => _isoDate,
  _isoDateTime: () => _isoDateTime,
  _isoDuration: () => _isoDuration,
  _isoTime: () => _isoTime,
  _jwt: () => _jwt,
  _ksuid: () => _ksuid,
  _lazy: () => _lazy,
  _length: () => _length,
  _literal: () => _literal,
  _lowercase: () => _lowercase,
  _lt: () => _lt,
  _lte: () => _lte,
  _mac: () => _mac,
  _map: () => _map,
  _max: () => _lte,
  _maxLength: () => _maxLength,
  _maxSize: () => _maxSize,
  _mime: () => _mime,
  _min: () => _gte,
  _minLength: () => _minLength,
  _minSize: () => _minSize,
  _multipleOf: () => _multipleOf,
  _nan: () => _nan,
  _nanoid: () => _nanoid,
  _nativeEnum: () => _nativeEnum,
  _negative: () => _negative,
  _never: () => _never,
  _nonnegative: () => _nonnegative,
  _nonoptional: () => _nonoptional,
  _nonpositive: () => _nonpositive,
  _normalize: () => _normalize,
  _null: () => _null2,
  _nullable: () => _nullable,
  _number: () => _number,
  _optional: () => _optional,
  _overwrite: () => _overwrite,
  _parse: () => _parse,
  _parseAsync: () => _parseAsync,
  _pipe: () => _pipe,
  _positive: () => _positive,
  _promise: () => _promise,
  _property: () => _property,
  _readonly: () => _readonly,
  _record: () => _record,
  _refine: () => _refine,
  _regex: () => _regex,
  _safeDecode: () => _safeDecode,
  _safeDecodeAsync: () => _safeDecodeAsync,
  _safeEncode: () => _safeEncode,
  _safeEncodeAsync: () => _safeEncodeAsync,
  _safeParse: () => _safeParse,
  _safeParseAsync: () => _safeParseAsync,
  _set: () => _set,
  _size: () => _size,
  _slugify: () => _slugify,
  _startsWith: () => _startsWith,
  _string: () => _string,
  _stringFormat: () => _stringFormat,
  _stringbool: () => _stringbool,
  _success: () => _success,
  _superRefine: () => _superRefine,
  _symbol: () => _symbol,
  _templateLiteral: () => _templateLiteral,
  _toLowerCase: () => _toLowerCase,
  _toUpperCase: () => _toUpperCase,
  _transform: () => _transform,
  _trim: () => _trim,
  _tuple: () => _tuple,
  _uint32: () => _uint32,
  _uint64: () => _uint64,
  _ulid: () => _ulid,
  _undefined: () => _undefined2,
  _union: () => _union,
  _unknown: () => _unknown,
  _uppercase: () => _uppercase,
  _url: () => _url,
  _uuid: () => _uuid,
  _uuidv4: () => _uuidv4,
  _uuidv6: () => _uuidv6,
  _uuidv7: () => _uuidv7,
  _void: () => _void,
  _xid: () => _xid,
  _xor: () => _xor,
  clone: () => clone2,
  config: () => config,
  createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod,
  createToJSONSchemaMethod: () => createToJSONSchemaMethod,
  decode: () => decode,
  decodeAsync: () => decodeAsync,
  describe: () => describe,
  encode: () => encode,
  encodeAsync: () => encodeAsync,
  extractDefs: () => extractDefs,
  finalize: () => finalize,
  flattenError: () => flattenError,
  formatError: () => formatError,
  globalConfig: () => globalConfig,
  globalRegistry: () => globalRegistry,
  initializeContext: () => initializeContext,
  isValidBase64: () => isValidBase64,
  isValidBase64URL: () => isValidBase64URL,
  isValidJWT: () => isValidJWT,
  locales: () => locales_exports,
  meta: () => meta,
  parse: () => parse3,
  parseAsync: () => parseAsync,
  prettifyError: () => prettifyError,
  process: () => process2,
  regexes: () => regexes_exports,
  registry: () => registry,
  safeDecode: () => safeDecode,
  safeDecodeAsync: () => safeDecodeAsync,
  safeEncode: () => safeEncode,
  safeEncodeAsync: () => safeEncodeAsync,
  safeParse: () => safeParse,
  safeParseAsync: () => safeParseAsync,
  toDotPath: () => toDotPath,
  toJSONSchema: () => toJSONSchema,
  treeifyError: () => treeifyError,
  util: () => util_exports2,
  version: () => version2
});

// node_modules/zod/v4/core/core.js
var _a;
var NEVER = /* @__PURE__ */ Object.freeze({
  status: "aborted"
});
// @__NO_SIDE_EFFECTS__
function $constructor(name, initializer3, params) {
  function init2(inst, def) {
    if (!inst._zod) {
      Object.defineProperty(inst, "_zod", {
        value: {
          def,
          constr: _,
          traits: /* @__PURE__ */ new Set()
        },
        enumerable: false
      });
    }
    if (inst._zod.traits.has(name)) {
      return;
    }
    inst._zod.traits.add(name);
    initializer3(inst, def);
    const proto = _.prototype;
    const keys = Object.keys(proto);
    for (let i = 0; i < keys.length; i++) {
      const k = keys[i];
      if (!(k in inst)) {
        inst[k] = proto[k].bind(inst);
      }
    }
  }
  const Parent = params?.Parent ?? Object;
  class Definition extends Parent {
  }
  Object.defineProperty(Definition, "name", { value: name });
  function _(def) {
    var _a3;
    const inst = params?.Parent ? new Definition() : this;
    init2(inst, def);
    (_a3 = inst._zod).deferred ?? (_a3.deferred = []);
    for (const fn of inst._zod.deferred) {
      fn();
    }
    return inst;
  }
  Object.defineProperty(_, "init", { value: init2 });
  Object.defineProperty(_, Symbol.hasInstance, {
    value: (inst) => {
      if (params?.Parent && inst instanceof params.Parent)
        return true;
      return inst?._zod?.traits?.has(name);
    }
  });
  Object.defineProperty(_, "name", { value: name });
  return _;
}
var $brand = /* @__PURE__ */ Symbol("zod_brand");
var $ZodAsyncError = class extends Error {
  constructor() {
    super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
  }
};
var $ZodEncodeError = class extends Error {
  constructor(name) {
    super(`Encountered unidirectional transform during encode: ${name}`);
    this.name = "ZodEncodeError";
  }
};
(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
var globalConfig = globalThis.__zod_globalConfig;
function config(newConfig) {
  if (newConfig)
    Object.assign(globalConfig, newConfig);
  return globalConfig;
}

// node_modules/zod/v4/core/util.js
var util_exports2 = {};
__export(util_exports2, {
  BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES,
  Class: () => Class,
  NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES,
  aborted: () => aborted,
  allowsEval: () => allowsEval,
  assert: () => assert,
  assertEqual: () => assertEqual,
  assertIs: () => assertIs,
  assertNever: () => assertNever,
  assertNotEqual: () => assertNotEqual,
  assignProp: () => assignProp,
  base64ToUint8Array: () => base64ToUint8Array,
  base64urlToUint8Array: () => base64urlToUint8Array,
  cached: () => cached,
  captureStackTrace: () => captureStackTrace,
  cleanEnum: () => cleanEnum,
  cleanRegex: () => cleanRegex,
  clone: () => clone2,
  cloneDef: () => cloneDef,
  createTransparentProxy: () => createTransparentProxy,
  defineLazy: () => defineLazy,
  esc: () => esc,
  escapeRegex: () => escapeRegex,
  explicitlyAborted: () => explicitlyAborted,
  extend: () => extend2,
  finalizeIssue: () => finalizeIssue,
  floatSafeRemainder: () => floatSafeRemainder,
  getElementAtPath: () => getElementAtPath,
  getEnumValues: () => getEnumValues,
  getLengthableOrigin: () => getLengthableOrigin,
  getParsedType: () => getParsedType,
  getSizableOrigin: () => getSizableOrigin,
  hexToUint8Array: () => hexToUint8Array,
  isObject: () => isObject2,
  isPlainObject: () => isPlainObject,
  issue: () => issue,
  joinValues: () => joinValues,
  jsonStringifyReplacer: () => jsonStringifyReplacer,
  merge: () => merge3,
  mergeDefs: () => mergeDefs,
  normalizeParams: () => normalizeParams,
  nullish: () => nullish,
  numKeys: () => numKeys,
  objectClone: () => objectClone,
  omit: () => omit,
  optionalKeys: () => optionalKeys,
  parsedType: () => parsedType,
  partial: () => partial,
  pick: () => pick2,
  prefixIssues: () => prefixIssues,
  primitiveTypes: () => primitiveTypes,
  promiseAllObject: () => promiseAllObject,
  propertyKeyTypes: () => propertyKeyTypes,
  randomString: () => randomString,
  required: () => required,
  safeExtend: () => safeExtend,
  shallowClone: () => shallowClone,
  slugify: () => slugify,
  stringifyPrimitive: () => stringifyPrimitive,
  uint8ArrayToBase64: () => uint8ArrayToBase64,
  uint8ArrayToBase64url: () => uint8ArrayToBase64url,
  uint8ArrayToHex: () => uint8ArrayToHex,
  unwrapMessage: () => unwrapMessage
});
function assertEqual(val) {
  return val;
}
function assertNotEqual(val) {
  return val;
}
function assertIs(_arg) {
}
function assertNever(_x) {
  throw new Error("Unexpected value in exhaustive check");
}
function assert(_) {
}
function getEnumValues(entries) {
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
  const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
  return values;
}
function joinValues(array3, separator = "|") {
  return array3.map((val) => stringifyPrimitive(val)).join(separator);
}
function jsonStringifyReplacer(_, value) {
  if (typeof value === "bigint")
    return value.toString();
  return value;
}
function cached(getter) {
  const set4 = false;
  return {
    get value() {
      if (!set4) {
        const value = getter();
        Object.defineProperty(this, "value", { value });
        return value;
      }
      throw new Error("cached value already set");
    }
  };
}
function nullish(input) {
  return input === null || input === void 0;
}
function cleanRegex(source) {
  const start2 = source.startsWith("^") ? 1 : 0;
  const end = source.endsWith("$") ? source.length - 1 : source.length;
  return source.slice(start2, end);
}
function floatSafeRemainder(val, step) {
  const ratio = val / step;
  const roundedRatio = Math.round(ratio);
  const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
  if (Math.abs(ratio - roundedRatio) < tolerance)
    return 0;
  return ratio - roundedRatio;
}
var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
function defineLazy(object2, key, getter) {
  let value = void 0;
  Object.defineProperty(object2, key, {
    get() {
      if (value === EVALUATING) {
        return void 0;
      }
      if (value === void 0) {
        value = EVALUATING;
        value = getter();
      }
      return value;
    },
    set(v) {
      Object.defineProperty(object2, key, {
        value: v
        // configurable: true,
      });
    },
    configurable: true
  });
}
function objectClone(obj) {
  return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
}
function assignProp(target, prop, value) {
  Object.defineProperty(target, prop, {
    value,
    writable: true,
    enumerable: true,
    configurable: true
  });
}
function mergeDefs(...defs) {
  const mergedDescriptors = {};
  for (const def of defs) {
    const descriptors = Object.getOwnPropertyDescriptors(def);
    Object.assign(mergedDescriptors, descriptors);
  }
  return Object.defineProperties({}, mergedDescriptors);
}
function cloneDef(schema) {
  return mergeDefs(schema._zod.def);
}
function getElementAtPath(obj, path2) {
  if (!path2)
    return obj;
  return path2.reduce((acc, key) => acc?.[key], obj);
}
function promiseAllObject(promisesObj) {
  const keys = Object.keys(promisesObj);
  const promises = keys.map((key) => promisesObj[key]);
  return Promise.all(promises).then((results) => {
    const resolvedObj = {};
    for (let i = 0; i < keys.length; i++) {
      resolvedObj[keys[i]] = results[i];
    }
    return resolvedObj;
  });
}
function randomString(length = 10) {
  const chars = "abcdefghijklmnopqrstuvwxyz";
  let str = "";
  for (let i = 0; i < length; i++) {
    str += chars[Math.floor(Math.random() * chars.length)];
  }
  return str;
}
function esc(str) {
  return JSON.stringify(str);
}
function slugify(input) {
  return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
}
var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {
};
function isObject2(data) {
  return typeof data === "object" && data !== null && !Array.isArray(data);
}
var allowsEval = /* @__PURE__ */ cached(() => {
  if (globalConfig.jitless) {
    return false;
  }
  if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
    return false;
  }
  try {
    const F = Function;
    new F("");
    return true;
  } catch (_) {
    return false;
  }
});
function isPlainObject(o) {
  if (isObject2(o) === false)
    return false;
  const ctor = o.constructor;
  if (ctor === void 0)
    return true;
  if (typeof ctor !== "function")
    return true;
  const prot = ctor.prototype;
  if (isObject2(prot) === false)
    return false;
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
    return false;
  }
  return true;
}
function shallowClone(o) {
  if (isPlainObject(o))
    return { ...o };
  if (Array.isArray(o))
    return [...o];
  if (o instanceof Map)
    return new Map(o);
  if (o instanceof Set)
    return new Set(o);
  return o;
}
function numKeys(data) {
  let keyCount = 0;
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      keyCount++;
    }
  }
  return keyCount;
}
var getParsedType = (data) => {
  const t = typeof data;
  switch (t) {
    case "undefined":
      return "undefined";
    case "string":
      return "string";
    case "number":
      return Number.isNaN(data) ? "nan" : "number";
    case "boolean":
      return "boolean";
    case "function":
      return "function";
    case "bigint":
      return "bigint";
    case "symbol":
      return "symbol";
    case "object":
      if (Array.isArray(data)) {
        return "array";
      }
      if (data === null) {
        return "null";
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return "promise";
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return "map";
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return "set";
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return "date";
      }
      if (typeof File !== "undefined" && data instanceof File) {
        return "file";
      }
      return "object";
    default:
      throw new Error(`Unknown data type: ${t}`);
  }
};
var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
var primitiveTypes = /* @__PURE__ */ new Set([
  "string",
  "number",
  "bigint",
  "boolean",
  "symbol",
  "undefined"
]);
function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone2(inst, def, params) {
  const cl = new inst._zod.constr(def ?? inst._zod.def);
  if (!def || params?.parent)
    cl._zod.parent = inst;
  return cl;
}
function normalizeParams(_params) {
  const params = _params;
  if (!params)
    return {};
  if (typeof params === "string")
    return { error: () => params };
  if (params?.message !== void 0) {
    if (params?.error !== void 0)
      throw new Error("Cannot specify both `message` and `error` params");
    params.error = params.message;
  }
  delete params.message;
  if (typeof params.error === "string")
    return { ...params, error: () => params.error };
  return params;
}
function createTransparentProxy(getter) {
  let target;
  return new Proxy({}, {
    get(_, prop, receiver) {
      target ?? (target = getter());
      return Reflect.get(target, prop, receiver);
    },
    set(_, prop, value, receiver) {
      target ?? (target = getter());
      return Reflect.set(target, prop, value, receiver);
    },
    has(_, prop) {
      target ?? (target = getter());
      return Reflect.has(target, prop);
    },
    deleteProperty(_, prop) {
      target ?? (target = getter());
      return Reflect.deleteProperty(target, prop);
    },
    ownKeys(_) {
      target ?? (target = getter());
      return Reflect.ownKeys(target);
    },
    getOwnPropertyDescriptor(_, prop) {
      target ?? (target = getter());
      return Reflect.getOwnPropertyDescriptor(target, prop);
    },
    defineProperty(_, prop, descriptor) {
      target ?? (target = getter());
      return Reflect.defineProperty(target, prop, descriptor);
    }
  });
}
function stringifyPrimitive(value) {
  if (typeof value === "bigint")
    return value.toString() + "n";
  if (typeof value === "string")
    return `"${value}"`;
  return `${value}`;
}
function optionalKeys(shape) {
  return Object.keys(shape).filter((k) => {
    return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
  });
}
var NUMBER_FORMAT_RANGES = {
  safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
  int32: [-2147483648, 2147483647],
  uint32: [0, 4294967295],
  float32: [-34028234663852886e22, 34028234663852886e22],
  float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
};
var BIGINT_FORMAT_RANGES = {
  int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
  uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
};
function pick2(schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".pick() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const newShape = {};
      for (const key in mask) {
        if (!(key in currDef.shape)) {
          throw new Error(`Unrecognized key: "${key}"`);
        }
        if (!mask[key])
          continue;
        newShape[key] = currDef.shape[key];
      }
      assignProp(this, "shape", newShape);
      return newShape;
    },
    checks: []
  });
  return clone2(schema, def);
}
function omit(schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".omit() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const newShape = { ...schema._zod.def.shape };
      for (const key in mask) {
        if (!(key in currDef.shape)) {
          throw new Error(`Unrecognized key: "${key}"`);
        }
        if (!mask[key])
          continue;
        delete newShape[key];
      }
      assignProp(this, "shape", newShape);
      return newShape;
    },
    checks: []
  });
  return clone2(schema, def);
}
function extend2(schema, shape) {
  if (!isPlainObject(shape)) {
    throw new Error("Invalid input to extend: expected a plain object");
  }
  const checks = schema._zod.def.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    const existingShape = schema._zod.def.shape;
    for (const key in shape) {
      if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) {
        throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
      }
    }
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape };
      assignProp(this, "shape", _shape);
      return _shape;
    }
  });
  return clone2(schema, def);
}
function safeExtend(schema, shape) {
  if (!isPlainObject(shape)) {
    throw new Error("Invalid input to safeExtend: expected a plain object");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape };
      assignProp(this, "shape", _shape);
      return _shape;
    }
  });
  return clone2(schema, def);
}
function merge3(a, b) {
  if (a._zod.def.checks?.length) {
    throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
  }
  const def = mergeDefs(a._zod.def, {
    get shape() {
      const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    get catchall() {
      return b._zod.def.catchall;
    },
    checks: b._zod.def.checks ?? []
  });
  return clone2(a, def);
}
function partial(Class2, schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".partial() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const oldShape = schema._zod.def.shape;
      const shape = { ...oldShape };
      if (mask) {
        for (const key in mask) {
          if (!(key in oldShape)) {
            throw new Error(`Unrecognized key: "${key}"`);
          }
          if (!mask[key])
            continue;
          shape[key] = Class2 ? new Class2({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      } else {
        for (const key in oldShape) {
          shape[key] = Class2 ? new Class2({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      }
      assignProp(this, "shape", shape);
      return shape;
    },
    checks: []
  });
  return clone2(schema, def);
}
function required(Class2, schema, mask) {
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const oldShape = schema._zod.def.shape;
      const shape = { ...oldShape };
      if (mask) {
        for (const key in mask) {
          if (!(key in shape)) {
            throw new Error(`Unrecognized key: "${key}"`);
          }
          if (!mask[key])
            continue;
          shape[key] = new Class2({
            type: "nonoptional",
            innerType: oldShape[key]
          });
        }
      } else {
        for (const key in oldShape) {
          shape[key] = new Class2({
            type: "nonoptional",
            innerType: oldShape[key]
          });
        }
      }
      assignProp(this, "shape", shape);
      return shape;
    }
  });
  return clone2(schema, def);
}
function aborted(x2, startIndex = 0) {
  if (x2.aborted === true)
    return true;
  for (let i = startIndex; i < x2.issues.length; i++) {
    if (x2.issues[i]?.continue !== true) {
      return true;
    }
  }
  return false;
}
function explicitlyAborted(x2, startIndex = 0) {
  if (x2.aborted === true)
    return true;
  for (let i = startIndex; i < x2.issues.length; i++) {
    if (x2.issues[i]?.continue === false) {
      return true;
    }
  }
  return false;
}
function prefixIssues(path2, issues) {
  return issues.map((iss) => {
    var _a3;
    (_a3 = iss).path ?? (_a3.path = []);
    iss.path.unshift(path2);
    return iss;
  });
}
function unwrapMessage(message) {
  return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config2) {
  const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
  const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
  rest.path ?? (rest.path = []);
  rest.message = message;
  if (ctx?.reportInput) {
    rest.input = _input;
  }
  return rest;
}
function getSizableOrigin(input) {
  if (input instanceof Set)
    return "set";
  if (input instanceof Map)
    return "map";
  if (input instanceof File)
    return "file";
  return "unknown";
}
function getLengthableOrigin(input) {
  if (Array.isArray(input))
    return "array";
  if (typeof input === "string")
    return "string";
  return "unknown";
}
function parsedType(data) {
  const t = typeof data;
  switch (t) {
    case "number": {
      return Number.isNaN(data) ? "nan" : "number";
    }
    case "object": {
      if (data === null) {
        return "null";
      }
      if (Array.isArray(data)) {
        return "array";
      }
      const obj = data;
      if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
        return obj.constructor.name;
      }
    }
  }
  return t;
}
function issue(...args) {
  const [iss, input, inst] = args;
  if (typeof iss === "string") {
    return {
      message: iss,
      code: "custom",
      input,
      inst
    };
  }
  return { ...iss };
}
function cleanEnum(obj) {
  return Object.entries(obj).filter(([k, _]) => {
    return Number.isNaN(Number.parseInt(k, 10));
  }).map((el) => el[1]);
}
function base64ToUint8Array(base643) {
  const binaryString = atob(base643);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes;
}
function uint8ArrayToBase64(bytes) {
  let binaryString = "";
  for (let i = 0; i < bytes.length; i++) {
    binaryString += String.fromCharCode(bytes[i]);
  }
  return btoa(binaryString);
}
function base64urlToUint8Array(base64url3) {
  const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
  const padding = "=".repeat((4 - base643.length % 4) % 4);
  return base64ToUint8Array(base643 + padding);
}
function uint8ArrayToBase64url(bytes) {
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function hexToUint8Array(hex4) {
  const cleanHex = hex4.replace(/^0x/, "");
  if (cleanHex.length % 2 !== 0) {
    throw new Error("Invalid hex string length");
  }
  const bytes = new Uint8Array(cleanHex.length / 2);
  for (let i = 0; i < cleanHex.length; i += 2) {
    bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
  }
  return bytes;
}
function uint8ArrayToHex(bytes) {
  return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
}
var Class = class {
  constructor(..._args) {
  }
};

// node_modules/zod/v4/core/errors.js
var initializer = (inst, def) => {
  inst.name = "$ZodError";
  Object.defineProperty(inst, "_zod", {
    value: inst._zod,
    enumerable: false
  });
  Object.defineProperty(inst, "issues", {
    value: def,
    enumerable: false
  });
  inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
  Object.defineProperty(inst, "toString", {
    value: () => inst.message,
    enumerable: false
  });
};
var $ZodError = $constructor("$ZodError", initializer);
var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
function flattenError(error51, mapper = (issue2) => issue2.message) {
  const fieldErrors = {};
  const formErrors = [];
  for (const sub of error51.issues) {
    if (sub.path.length > 0) {
      fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
      fieldErrors[sub.path[0]].push(mapper(sub));
    } else {
      formErrors.push(mapper(sub));
    }
  }
  return { formErrors, fieldErrors };
}
function formatError(error51, mapper = (issue2) => issue2.message) {
  const fieldErrors = { _errors: [] };
  const processError = (error52, path2 = []) => {
    for (const issue2 of error52.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }, [...path2, ...issue2.path]));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues }, [...path2, ...issue2.path]);
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues }, [...path2, ...issue2.path]);
      } else {
        const fullpath = [...path2, ...issue2.path];
        if (fullpath.length === 0) {
          fieldErrors._errors.push(mapper(issue2));
        } else {
          let curr = fieldErrors;
          let i = 0;
          while (i < fullpath.length) {
            const el = fullpath[i];
            const terminal = i === fullpath.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue2));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    }
  };
  processError(error51);
  return fieldErrors;
}
function treeifyError(error51, mapper = (issue2) => issue2.message) {
  const result = { errors: [] };
  const processError = (error52, path2 = []) => {
    var _a3, _b;
    for (const issue2 of error52.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }, [...path2, ...issue2.path]));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues }, [...path2, ...issue2.path]);
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues }, [...path2, ...issue2.path]);
      } else {
        const fullpath = [...path2, ...issue2.path];
        if (fullpath.length === 0) {
          result.errors.push(mapper(issue2));
          continue;
        }
        let curr = result;
        let i = 0;
        while (i < fullpath.length) {
          const el = fullpath[i];
          const terminal = i === fullpath.length - 1;
          if (typeof el === "string") {
            curr.properties ?? (curr.properties = {});
            (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] });
            curr = curr.properties[el];
          } else {
            curr.items ?? (curr.items = []);
            (_b = curr.items)[el] ?? (_b[el] = { errors: [] });
            curr = curr.items[el];
          }
          if (terminal) {
            curr.errors.push(mapper(issue2));
          }
          i++;
        }
      }
    }
  };
  processError(error51);
  return result;
}
function toDotPath(_path) {
  const segs = [];
  const path2 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
  for (const seg of path2) {
    if (typeof seg === "number")
      segs.push(`[${seg}]`);
    else if (typeof seg === "symbol")
      segs.push(`[${JSON.stringify(String(seg))}]`);
    else if (/[^\w$]/.test(seg))
      segs.push(`[${JSON.stringify(seg)}]`);
    else {
      if (segs.length)
        segs.push(".");
      segs.push(seg);
    }
  }
  return segs.join("");
}
function prettifyError(error51) {
  const lines = [];
  const issues = [...error51.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
  for (const issue2 of issues) {
    lines.push(`\u2716 ${issue2.message}`);
    if (issue2.path?.length)
      lines.push(`  \u2192 at ${toDotPath(issue2.path)}`);
  }
  return lines.join("\n");
}

// node_modules/zod/v4/core/parse.js
var _parse = (_Err) => (schema, value, _ctx, _params) => {
  const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
  const result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise) {
    throw new $ZodAsyncError();
  }
  if (result.issues.length) {
    const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e, _params?.callee);
    throw e;
  }
  return result.value;
};
var parse3 = /* @__PURE__ */ _parse($ZodRealError);
var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
  const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
  let result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise)
    result = await result;
  if (result.issues.length) {
    const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e, params?.callee);
    throw e;
  }
  return result.value;
};
var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);
var _safeParse = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
  const result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise) {
    throw new $ZodAsyncError();
  }
  return result.issues.length ? {
    success: false,
    error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  } : { success: true, data: result.value };
};
var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
  let result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise)
    result = await result;
  return result.issues.length ? {
    success: false,
    error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  } : { success: true, data: result.value };
};
var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
var _encode = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _parse(_Err)(schema, value, ctx);
};
var encode = /* @__PURE__ */ _encode($ZodRealError);
var _decode = (_Err) => (schema, value, _ctx) => {
  return _parse(_Err)(schema, value, _ctx);
};
var decode = /* @__PURE__ */ _decode($ZodRealError);
var _encodeAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _parseAsync(_Err)(schema, value, ctx);
};
var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError);
var _decodeAsync = (_Err) => async (schema, value, _ctx) => {
  return _parseAsync(_Err)(schema, value, _ctx);
};
var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError);
var _safeEncode = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _safeParse(_Err)(schema, value, ctx);
};
var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError);
var _safeDecode = (_Err) => (schema, value, _ctx) => {
  return _safeParse(_Err)(schema, value, _ctx);
};
var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError);
var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _safeParseAsync(_Err)(schema, value, ctx);
};
var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError);
var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
  return _safeParseAsync(_Err)(schema, value, _ctx);
};
var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError);

// node_modules/zod/v4/core/regexes.js
var regexes_exports = {};
__export(regexes_exports, {
  base64: () => base64,
  base64url: () => base64url,
  bigint: () => bigint,
  boolean: () => boolean,
  browserEmail: () => browserEmail,
  cidrv4: () => cidrv4,
  cidrv6: () => cidrv6,
  cuid: () => cuid,
  cuid2: () => cuid2,
  date: () => date2,
  datetime: () => datetime,
  domain: () => domain,
  duration: () => duration,
  e164: () => e164,
  email: () => email,
  emoji: () => emoji,
  extendedDuration: () => extendedDuration,
  guid: () => guid,
  hex: () => hex2,
  hostname: () => hostname,
  html5Email: () => html5Email,
  httpProtocol: () => httpProtocol,
  idnEmail: () => idnEmail,
  integer: () => integer,
  ipv4: () => ipv4,
  ipv6: () => ipv6,
  ksuid: () => ksuid,
  lowercase: () => lowercase,
  mac: () => mac,
  md5_base64: () => md5_base64,
  md5_base64url: () => md5_base64url,
  md5_hex: () => md5_hex,
  nanoid: () => nanoid,
  null: () => _null,
  number: () => number5,
  rfc5322Email: () => rfc5322Email,
  sha1_base64: () => sha1_base64,
  sha1_base64url: () => sha1_base64url,
  sha1_hex: () => sha1_hex,
  sha256_base64: () => sha256_base64,
  sha256_base64url: () => sha256_base64url,
  sha256_hex: () => sha256_hex,
  sha384_base64: () => sha384_base64,
  sha384_base64url: () => sha384_base64url,
  sha384_hex: () => sha384_hex,
  sha512_base64: () => sha512_base64,
  sha512_base64url: () => sha512_base64url,
  sha512_hex: () => sha512_hex,
  string: () => string,
  time: () => time,
  ulid: () => ulid,
  undefined: () => _undefined,
  unicodeEmail: () => unicodeEmail,
  uppercase: () => uppercase,
  uuid: () => uuid,
  uuid4: () => uuid4,
  uuid6: () => uuid6,
  uuid7: () => uuid7,
  xid: () => xid
});
var cuid = /^[cC][0-9a-z]{6,}$/;
var cuid2 = /^[0-9a-z]+$/;
var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
var xid = /^[0-9a-vA-V]{20}$/;
var ksuid = /^[A-Za-z0-9]{27}$/;
var nanoid = /^[a-zA-Z0-9_-]{21}$/;
var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
var uuid = (version3) => {
  if (!version3)
    return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
  return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
var uuid4 = /* @__PURE__ */ uuid(4);
var uuid6 = /* @__PURE__ */ uuid(6);
var uuid7 = /* @__PURE__ */ uuid(7);
var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
var idnEmail = unicodeEmail;
var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji() {
  return new RegExp(_emoji, "u");
}
var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
var mac = (delimiter) => {
  const escapedDelim = escapeRegex(delimiter ?? ":");
  return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
};
var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
var base64url = /^[A-Za-z0-9_-]*$/;
var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
var httpProtocol = /^https?$/;
var e164 = /^\+[1-9]\d{6,14}$/;
var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
var date2 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
function timeSource(args) {
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
  const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
  return regex;
}
function time(args) {
  return new RegExp(`^${timeSource(args)}$`);
}
function datetime(args) {
  const time3 = timeSource({ precision: args.precision });
  const opts = ["Z"];
  if (args.local)
    opts.push("");
  if (args.offset)
    opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
  const timeRegex = `${time3}(?:${opts.join("|")})`;
  return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
var string = (params) => {
  const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
  return new RegExp(`^${regex}$`);
};
var bigint = /^-?\d+n?$/;
var integer = /^-?\d+$/;
var number5 = /^-?\d+(?:\.\d+)?$/;
var boolean = /^(?:true|false)$/i;
var _null = /^null$/i;
var _undefined = /^undefined$/i;
var lowercase = /^[^A-Z]*$/;
var uppercase = /^[^a-z]*$/;
var hex2 = /^[0-9a-fA-F]*$/;
function fixedBase64(bodyLength, padding) {
  return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
}
function fixedBase64url(length) {
  return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);
}
var md5_hex = /^[0-9a-fA-F]{32}$/;
var md5_base64 = /* @__PURE__ */ fixedBase64(22, "==");
var md5_base64url = /* @__PURE__ */ fixedBase64url(22);
var sha1_hex = /^[0-9a-fA-F]{40}$/;
var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "=");
var sha1_base64url = /* @__PURE__ */ fixedBase64url(27);
var sha256_hex = /^[0-9a-fA-F]{64}$/;
var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "=");
var sha256_base64url = /* @__PURE__ */ fixedBase64url(43);
var sha384_hex = /^[0-9a-fA-F]{96}$/;
var sha384_base64 = /* @__PURE__ */ fixedBase64(64, "");
var sha384_base64url = /* @__PURE__ */ fixedBase64url(64);
var sha512_hex = /^[0-9a-fA-F]{128}$/;
var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "==");
var sha512_base64url = /* @__PURE__ */ fixedBase64url(86);

// node_modules/zod/v4/core/checks.js
var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
  var _a3;
  inst._zod ?? (inst._zod = {});
  inst._zod.def = def;
  (_a3 = inst._zod).onattach ?? (_a3.onattach = []);
});
var numericOriginMap = {
  number: "number",
  bigint: "bigint",
  object: "date"
};
var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
  $ZodCheck.init(inst, def);
  const origin = numericOriginMap[typeof def.value];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
    if (def.value < curr) {
      if (def.inclusive)
        bag.maximum = def.value;
      else
        bag.exclusiveMaximum = def.value;
    }
  });
  inst._zod.check = (payload) => {
    if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
      return;
    }
    payload.issues.push({
      origin,
      code: "too_big",
      maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
      input: payload.value,
      inclusive: def.inclusive,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
  $ZodCheck.init(inst, def);
  const origin = numericOriginMap[typeof def.value];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
    if (def.value > curr) {
      if (def.inclusive)
        bag.minimum = def.value;
      else
        bag.exclusiveMinimum = def.value;
    }
  });
  inst._zod.check = (payload) => {
    if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
      return;
    }
    payload.issues.push({
      origin,
      code: "too_small",
      minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
      input: payload.value,
      inclusive: def.inclusive,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    var _a3;
    (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value);
  });
  inst._zod.check = (payload) => {
    if (typeof payload.value !== typeof def.value)
      throw new Error("Cannot mix number and bigint in multiple_of check.");
    const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
    if (isMultiple)
      return;
    payload.issues.push({
      origin: typeof payload.value,
      code: "not_multiple_of",
      divisor: def.value,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
  $ZodCheck.init(inst, def);
  def.format = def.format || "float64";
  const isInt = def.format?.includes("int");
  const origin = isInt ? "int" : "number";
  const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    bag.minimum = minimum;
    bag.maximum = maximum;
    if (isInt)
      bag.pattern = integer;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    if (isInt) {
      if (!Number.isInteger(input)) {
        payload.issues.push({
          expected: origin,
          format: def.format,
          code: "invalid_type",
          continue: false,
          input,
          inst
        });
        return;
      }
      if (!Number.isSafeInteger(input)) {
        if (input > 0) {
          payload.issues.push({
            input,
            code: "too_big",
            maximum: Number.MAX_SAFE_INTEGER,
            note: "Integers must be within the safe integer range.",
            inst,
            origin,
            inclusive: true,
            continue: !def.abort
          });
        } else {
          payload.issues.push({
            input,
            code: "too_small",
            minimum: Number.MIN_SAFE_INTEGER,
            note: "Integers must be within the safe integer range.",
            inst,
            origin,
            inclusive: true,
            continue: !def.abort
          });
        }
        return;
      }
    }
    if (input < minimum) {
      payload.issues.push({
        origin: "number",
        input,
        code: "too_small",
        minimum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
    if (input > maximum) {
      payload.issues.push({
        origin: "number",
        input,
        code: "too_big",
        maximum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => {
  $ZodCheck.init(inst, def);
  const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    bag.minimum = minimum;
    bag.maximum = maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    if (input < minimum) {
      payload.issues.push({
        origin: "bigint",
        input,
        code: "too_small",
        minimum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
    if (input > maximum) {
      payload.issues.push({
        origin: "bigint",
        input,
        code: "too_big",
        maximum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
    if (def.maximum < curr)
      inst2._zod.bag.maximum = def.maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size = input.size;
    if (size <= def.maximum)
      return;
    payload.issues.push({
      origin: getSizableOrigin(input),
      code: "too_big",
      maximum: def.maximum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
    if (def.minimum > curr)
      inst2._zod.bag.minimum = def.minimum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size = input.size;
    if (size >= def.minimum)
      return;
    payload.issues.push({
      origin: getSizableOrigin(input),
      code: "too_small",
      minimum: def.minimum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.minimum = def.size;
    bag.maximum = def.size;
    bag.size = def.size;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size = input.size;
    if (size === def.size)
      return;
    const tooBig = size > def.size;
    payload.issues.push({
      origin: getSizableOrigin(input),
      ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size },
      inclusive: true,
      exact: true,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
    if (def.maximum < curr)
      inst2._zod.bag.maximum = def.maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length <= def.maximum)
      return;
    const origin = getLengthableOrigin(input);
    payload.issues.push({
      origin,
      code: "too_big",
      maximum: def.maximum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
    if (def.minimum > curr)
      inst2._zod.bag.minimum = def.minimum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length >= def.minimum)
      return;
    const origin = getLengthableOrigin(input);
    payload.issues.push({
      origin,
      code: "too_small",
      minimum: def.minimum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.minimum = def.length;
    bag.maximum = def.length;
    bag.length = def.length;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length === def.length)
      return;
    const origin = getLengthableOrigin(input);
    const tooBig = length > def.length;
    payload.issues.push({
      origin,
      ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },
      inclusive: true,
      exact: true,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
  var _a3, _b;
  $ZodCheck.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    if (def.pattern) {
      bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
      bag.patterns.add(def.pattern);
    }
  });
  if (def.pattern)
    (_a3 = inst._zod).check ?? (_a3.check = (payload) => {
      def.pattern.lastIndex = 0;
      if (def.pattern.test(payload.value))
        return;
      payload.issues.push({
        origin: "string",
        code: "invalid_format",
        format: def.format,
        input: payload.value,
        ...def.pattern ? { pattern: def.pattern.toString() } : {},
        inst,
        continue: !def.abort
      });
    });
  else
    (_b = inst._zod).check ?? (_b.check = () => {
    });
});
var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
  $ZodCheckStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    def.pattern.lastIndex = 0;
    if (def.pattern.test(payload.value))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "regex",
      input: payload.value,
      pattern: def.pattern.toString(),
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
  def.pattern ?? (def.pattern = lowercase);
  $ZodCheckStringFormat.init(inst, def);
});
var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
  def.pattern ?? (def.pattern = uppercase);
  $ZodCheckStringFormat.init(inst, def);
});
var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
  $ZodCheck.init(inst, def);
  const escapedRegex = escapeRegex(def.includes);
  const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
  def.pattern = pattern;
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.includes(def.includes, def.position))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "includes",
      includes: def.includes,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
  $ZodCheck.init(inst, def);
  const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
  def.pattern ?? (def.pattern = pattern);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.startsWith(def.prefix))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "starts_with",
      prefix: def.prefix,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
  $ZodCheck.init(inst, def);
  const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
  def.pattern ?? (def.pattern = pattern);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.endsWith(def.suffix))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "ends_with",
      suffix: def.suffix,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
function handleCheckPropertyResult(result, payload, property) {
  if (result.issues.length) {
    payload.issues.push(...prefixIssues(property, result.issues));
  }
}
var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.check = (payload) => {
    const result = def.schema._zod.run({
      value: payload.value[def.property],
      issues: []
    }, {});
    if (result instanceof Promise) {
      return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property));
    }
    handleCheckPropertyResult(result, payload, def.property);
    return;
  };
});
var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => {
  $ZodCheck.init(inst, def);
  const mimeSet = new Set(def.mime);
  inst._zod.onattach.push((inst2) => {
    inst2._zod.bag.mime = def.mime;
  });
  inst._zod.check = (payload) => {
    if (mimeSet.has(payload.value.type))
      return;
    payload.issues.push({
      code: "invalid_value",
      values: def.mime,
      input: payload.value.type,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.check = (payload) => {
    payload.value = def.tx(payload.value);
  };
});

// node_modules/zod/v4/core/doc.js
var Doc = class {
  constructor(args = []) {
    this.content = [];
    this.indent = 0;
    if (this)
      this.args = args;
  }
  indented(fn) {
    this.indent += 1;
    fn(this);
    this.indent -= 1;
  }
  write(arg) {
    if (typeof arg === "function") {
      arg(this, { execution: "sync" });
      arg(this, { execution: "async" });
      return;
    }
    const content = arg;
    const lines = content.split("\n").filter((x2) => x2);
    const minIndent = Math.min(...lines.map((x2) => x2.length - x2.trimStart().length));
    const dedented = lines.map((x2) => x2.slice(minIndent)).map((x2) => " ".repeat(this.indent * 2) + x2);
    for (const line of dedented) {
      this.content.push(line);
    }
  }
  compile() {
    const F = Function;
    const args = this?.args;
    const content = this?.content ?? [``];
    const lines = [...content.map((x2) => `  ${x2}`)];
    return new F(...args, lines.join("\n"));
  }
};

// node_modules/zod/v4/core/versions.js
var version2 = {
  major: 4,
  minor: 4,
  patch: 3
};

// node_modules/zod/v4/core/schemas.js
var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
  var _a3;
  inst ?? (inst = {});
  inst._zod.def = def;
  inst._zod.bag = inst._zod.bag || {};
  inst._zod.version = version2;
  const checks = [...inst._zod.def.checks ?? []];
  if (inst._zod.traits.has("$ZodCheck")) {
    checks.unshift(inst);
  }
  for (const ch of checks) {
    for (const fn of ch._zod.onattach) {
      fn(inst);
    }
  }
  if (checks.length === 0) {
    (_a3 = inst._zod).deferred ?? (_a3.deferred = []);
    inst._zod.deferred?.push(() => {
      inst._zod.run = inst._zod.parse;
    });
  } else {
    const runChecks = (payload, checks2, ctx) => {
      let isAborted = aborted(payload);
      let asyncResult;
      for (const ch of checks2) {
        if (ch._zod.def.when) {
          if (explicitlyAborted(payload))
            continue;
          const shouldRun = ch._zod.def.when(payload);
          if (!shouldRun)
            continue;
        } else if (isAborted) {
          continue;
        }
        const currLen = payload.issues.length;
        const _ = ch._zod.check(payload);
        if (_ instanceof Promise && ctx?.async === false) {
          throw new $ZodAsyncError();
        }
        if (asyncResult || _ instanceof Promise) {
          asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
            await _;
            const nextLen = payload.issues.length;
            if (nextLen === currLen)
              return;
            if (!isAborted)
              isAborted = aborted(payload, currLen);
          });
        } else {
          const nextLen = payload.issues.length;
          if (nextLen === currLen)
            continue;
          if (!isAborted)
            isAborted = aborted(payload, currLen);
        }
      }
      if (asyncResult) {
        return asyncResult.then(() => {
          return payload;
        });
      }
      return payload;
    };
    const handleCanaryResult = (canary, payload, ctx) => {
      if (aborted(canary)) {
        canary.aborted = true;
        return canary;
      }
      const checkResult = runChecks(payload, checks, ctx);
      if (checkResult instanceof Promise) {
        if (ctx.async === false)
          throw new $ZodAsyncError();
        return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx));
      }
      return inst._zod.parse(checkResult, ctx);
    };
    inst._zod.run = (payload, ctx) => {
      if (ctx.skipChecks) {
        return inst._zod.parse(payload, ctx);
      }
      if (ctx.direction === "backward") {
        const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
        if (canary instanceof Promise) {
          return canary.then((canary2) => {
            return handleCanaryResult(canary2, payload, ctx);
          });
        }
        return handleCanaryResult(canary, payload, ctx);
      }
      const result = inst._zod.parse(payload, ctx);
      if (result instanceof Promise) {
        if (ctx.async === false)
          throw new $ZodAsyncError();
        return result.then((result2) => runChecks(result2, checks, ctx));
      }
      return runChecks(result, checks, ctx);
    };
  }
  defineLazy(inst, "~standard", () => ({
    validate: (value) => {
      try {
        const r = safeParse(inst, value);
        return r.success ? { value: r.data } : { issues: r.error?.issues };
      } catch (_) {
        return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
      }
    },
    vendor: "zod",
    version: 1
  }));
});
var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
  inst._zod.parse = (payload, _) => {
    if (def.coerce)
      try {
        payload.value = String(payload.value);
      } catch (_2) {
      }
    if (typeof payload.value === "string")
      return payload;
    payload.issues.push({
      expected: "string",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
  $ZodCheckStringFormat.init(inst, def);
  $ZodString.init(inst, def);
});
var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
  def.pattern ?? (def.pattern = guid);
  $ZodStringFormat.init(inst, def);
});
var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
  if (def.version) {
    const versionMap = {
      v1: 1,
      v2: 2,
      v3: 3,
      v4: 4,
      v5: 5,
      v6: 6,
      v7: 7,
      v8: 8
    };
    const v = versionMap[def.version];
    if (v === void 0)
      throw new Error(`Invalid UUID version: "${def.version}"`);
    def.pattern ?? (def.pattern = uuid(v));
  } else
    def.pattern ?? (def.pattern = uuid());
  $ZodStringFormat.init(inst, def);
});
var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
  def.pattern ?? (def.pattern = email);
  $ZodStringFormat.init(inst, def);
});
var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    try {
      const trimmed = payload.value.trim();
      if (!def.normalize && def.protocol?.source === httpProtocol.source) {
        if (!/^https?:\/\//i.test(trimmed)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid URL format",
            input: payload.value,
            inst,
            continue: !def.abort
          });
          return;
        }
      }
      const url2 = new URL(trimmed);
      if (def.hostname) {
        def.hostname.lastIndex = 0;
        if (!def.hostname.test(url2.hostname)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid hostname",
            pattern: def.hostname.source,
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      }
      if (def.protocol) {
        def.protocol.lastIndex = 0;
        if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid protocol",
            pattern: def.protocol.source,
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      }
      if (def.normalize) {
        payload.value = url2.href;
      } else {
        payload.value = trimmed;
      }
      return;
    } catch (_) {
      payload.issues.push({
        code: "invalid_format",
        format: "url",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
  def.pattern ?? (def.pattern = emoji());
  $ZodStringFormat.init(inst, def);
});
var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
  def.pattern ?? (def.pattern = nanoid);
  $ZodStringFormat.init(inst, def);
});
var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
  def.pattern ?? (def.pattern = cuid);
  $ZodStringFormat.init(inst, def);
});
var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
  def.pattern ?? (def.pattern = cuid2);
  $ZodStringFormat.init(inst, def);
});
var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
  def.pattern ?? (def.pattern = ulid);
  $ZodStringFormat.init(inst, def);
});
var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
  def.pattern ?? (def.pattern = xid);
  $ZodStringFormat.init(inst, def);
});
var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
  def.pattern ?? (def.pattern = ksuid);
  $ZodStringFormat.init(inst, def);
});
var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
  def.pattern ?? (def.pattern = datetime(def));
  $ZodStringFormat.init(inst, def);
});
var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
  def.pattern ?? (def.pattern = date2);
  $ZodStringFormat.init(inst, def);
});
var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
  def.pattern ?? (def.pattern = time(def));
  $ZodStringFormat.init(inst, def);
});
var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
  def.pattern ?? (def.pattern = duration);
  $ZodStringFormat.init(inst, def);
});
var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
  def.pattern ?? (def.pattern = ipv4);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `ipv4`;
});
var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
  def.pattern ?? (def.pattern = ipv6);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `ipv6`;
  inst._zod.check = (payload) => {
    try {
      new URL(`http://[${payload.value}]`);
    } catch {
      payload.issues.push({
        code: "invalid_format",
        format: "ipv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => {
  def.pattern ?? (def.pattern = mac(def.delimiter));
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `mac`;
});
var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
  def.pattern ?? (def.pattern = cidrv4);
  $ZodStringFormat.init(inst, def);
});
var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
  def.pattern ?? (def.pattern = cidrv6);
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    const parts = payload.value.split("/");
    try {
      if (parts.length !== 2)
        throw new Error();
      const [address, prefix] = parts;
      if (!prefix)
        throw new Error();
      const prefixNum = Number(prefix);
      if (`${prefixNum}` !== prefix)
        throw new Error();
      if (prefixNum < 0 || prefixNum > 128)
        throw new Error();
      new URL(`http://[${address}]`);
    } catch {
      payload.issues.push({
        code: "invalid_format",
        format: "cidrv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
function isValidBase64(data) {
  if (data === "")
    return true;
  if (/\s/.test(data))
    return false;
  if (data.length % 4 !== 0)
    return false;
  try {
    atob(data);
    return true;
  } catch {
    return false;
  }
}
var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
  def.pattern ?? (def.pattern = base64);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.contentEncoding = "base64";
  inst._zod.check = (payload) => {
    if (isValidBase64(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
function isValidBase64URL(data) {
  if (!base64url.test(data))
    return false;
  const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
  const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
  return isValidBase64(padded);
}
var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
  def.pattern ?? (def.pattern = base64url);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.contentEncoding = "base64url";
  inst._zod.check = (payload) => {
    if (isValidBase64URL(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64url",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
  def.pattern ?? (def.pattern = e164);
  $ZodStringFormat.init(inst, def);
});
function isValidJWT(token, algorithm = null) {
  try {
    const tokensParts = token.split(".");
    if (tokensParts.length !== 3)
      return false;
    const [header] = tokensParts;
    if (!header)
      return false;
    const parsedHeader = JSON.parse(atob(header));
    if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
      return false;
    if (!parsedHeader.alg)
      return false;
    if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
      return false;
    return true;
  } catch {
    return false;
  }
}
var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (isValidJWT(payload.value, def.alg))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "jwt",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (def.fn(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: def.format,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = inst._zod.bag.pattern ?? number5;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Number(payload.value);
      } catch (_) {
      }
    const input = payload.value;
    if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
      return payload;
    }
    const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
    payload.issues.push({
      expected: "number",
      code: "invalid_type",
      input,
      inst,
      ...received ? { received } : {}
    });
    return payload;
  };
});
var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => {
  $ZodCheckNumberFormat.init(inst, def);
  $ZodNumber.init(inst, def);
});
var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = boolean;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Boolean(payload.value);
      } catch (_) {
      }
    const input = payload.value;
    if (typeof input === "boolean")
      return payload;
    payload.issues.push({
      expected: "boolean",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = bigint;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = BigInt(payload.value);
      } catch (_) {
      }
    if (typeof payload.value === "bigint")
      return payload;
    payload.issues.push({
      expected: "bigint",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => {
  $ZodCheckBigIntFormat.init(inst, def);
  $ZodBigInt.init(inst, def);
});
var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "symbol")
      return payload;
    payload.issues.push({
      expected: "symbol",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = _undefined;
  inst._zod.values = /* @__PURE__ */ new Set([void 0]);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "undefined")
      return payload;
    payload.issues.push({
      expected: "undefined",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = _null;
  inst._zod.values = /* @__PURE__ */ new Set([null]);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (input === null)
      return payload;
    payload.issues.push({
      expected: "null",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    payload.issues.push({
      expected: "never",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "undefined")
      return payload;
    payload.issues.push({
      expected: "void",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce) {
      try {
        payload.value = new Date(payload.value);
      } catch (_err) {
      }
    }
    const input = payload.value;
    const isDate2 = input instanceof Date;
    const isValidDate = isDate2 && !Number.isNaN(input.getTime());
    if (isValidDate)
      return payload;
    payload.issues.push({
      expected: "date",
      code: "invalid_type",
      input,
      ...isDate2 ? { received: "Invalid Date" } : {},
      inst
    });
    return payload;
  };
});
function handleArrayResult(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}
var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!Array.isArray(input)) {
      payload.issues.push({
        expected: "array",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    payload.value = Array(input.length);
    const proms = [];
    for (let i = 0; i < input.length; i++) {
      const item = input[i];
      const result = def.element._zod.run({
        value: item,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleArrayResult(result2, payload, i)));
      } else {
        handleArrayResult(result, payload, i);
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
  const isPresent = key in input;
  if (result.issues.length) {
    if (isOptionalIn && isOptionalOut && !isPresent) {
      return;
    }
    final.issues.push(...prefixIssues(key, result.issues));
  }
  if (!isPresent && !isOptionalIn) {
    if (!result.issues.length) {
      final.issues.push({
        code: "invalid_type",
        expected: "nonoptional",
        input: void 0,
        path: [key]
      });
    }
    return;
  }
  if (result.value === void 0) {
    if (isPresent) {
      final.value[key] = void 0;
    }
  } else {
    final.value[key] = result.value;
  }
}
function normalizeDef(def) {
  const keys = Object.keys(def.shape);
  for (const k of keys) {
    if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
      throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
    }
  }
  const okeys = optionalKeys(def.shape);
  return {
    ...def,
    keys,
    keySet: new Set(keys),
    numKeys: keys.length,
    optionalKeys: new Set(okeys)
  };
}
function handleCatchall(proms, input, payload, ctx, def, inst) {
  const unrecognized = [];
  const keySet = def.keySet;
  const _catchall = def.catchall._zod;
  const t = _catchall.def.type;
  const isOptionalIn = _catchall.optin === "optional";
  const isOptionalOut = _catchall.optout === "optional";
  for (const key in input) {
    if (key === "__proto__")
      continue;
    if (keySet.has(key))
      continue;
    if (t === "never") {
      unrecognized.push(key);
      continue;
    }
    const r = _catchall.run({ value: input[key], issues: [] }, ctx);
    if (r instanceof Promise) {
      proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut)));
    } else {
      handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
    }
  }
  if (unrecognized.length) {
    payload.issues.push({
      code: "unrecognized_keys",
      keys: unrecognized,
      input,
      inst
    });
  }
  if (!proms.length)
    return payload;
  return Promise.all(proms).then(() => {
    return payload;
  });
}
var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
  $ZodType.init(inst, def);
  const desc = Object.getOwnPropertyDescriptor(def, "shape");
  if (!desc?.get) {
    const sh = def.shape;
    Object.defineProperty(def, "shape", {
      get: () => {
        const newSh = { ...sh };
        Object.defineProperty(def, "shape", {
          value: newSh
        });
        return newSh;
      }
    });
  }
  const _normalized = cached(() => normalizeDef(def));
  defineLazy(inst._zod, "propValues", () => {
    const shape = def.shape;
    const propValues = {};
    for (const key in shape) {
      const field = shape[key]._zod;
      if (field.values) {
        propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
        for (const v of field.values)
          propValues[key].add(v);
      }
    }
    return propValues;
  });
  const isObject3 = isObject2;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value ?? (value = _normalized.value);
    const input = payload.value;
    if (!isObject3(input)) {
      payload.issues.push({
        expected: "object",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    payload.value = {};
    const proms = [];
    const shape = value.shape;
    for (const key of value.keys) {
      const el = shape[key];
      const isOptionalIn = el._zod.optin === "optional";
      const isOptionalOut = el._zod.optout === "optional";
      const r = el._zod.run({ value: input[key], issues: [] }, ctx);
      if (r instanceof Promise) {
        proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut)));
      } else {
        handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
      }
    }
    if (!catchall) {
      return proms.length ? Promise.all(proms).then(() => payload) : payload;
    }
    return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
  };
});
var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
  $ZodObject.init(inst, def);
  const superParse = inst._zod.parse;
  const _normalized = cached(() => normalizeDef(def));
  const generateFastpass = (shape) => {
    const doc = new Doc(["shape", "payload", "ctx"]);
    const normalized = _normalized.value;
    const parseStr = (key) => {
      const k = esc(key);
      return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
    };
    doc.write(`const input = payload.value;`);
    const ids = /* @__PURE__ */ Object.create(null);
    let counter = 0;
    for (const key of normalized.keys) {
      ids[key] = `key_${counter++}`;
    }
    doc.write(`const newResult = {};`);
    for (const key of normalized.keys) {
      const id2 = ids[key];
      const k = esc(key);
      const schema = shape[key];
      const isOptionalIn = schema?._zod?.optin === "optional";
      const isOptionalOut = schema?._zod?.optout === "optional";
      doc.write(`const ${id2} = ${parseStr(key)};`);
      if (isOptionalIn && isOptionalOut) {
        doc.write(`
        if (${id2}.issues.length) {
          if (${k} in input) {
            payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
              ...iss,
              path: iss.path ? [${k}, ...iss.path] : [${k}]
            })));
          }
        }
        
        if (${id2}.value === undefined) {
          if (${k} in input) {
            newResult[${k}] = undefined;
          }
        } else {
          newResult[${k}] = ${id2}.value;
        }
        
      `);
      } else if (!isOptionalIn) {
        doc.write(`
        const ${id2}_present = ${k} in input;
        if (${id2}.issues.length) {
          payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${k}, ...iss.path] : [${k}]
          })));
        }
        if (!${id2}_present && !${id2}.issues.length) {
          payload.issues.push({
            code: "invalid_type",
            expected: "nonoptional",
            input: undefined,
            path: [${k}]
          });
        }

        if (${id2}_present) {
          if (${id2}.value === undefined) {
            newResult[${k}] = undefined;
          } else {
            newResult[${k}] = ${id2}.value;
          }
        }

      `);
      } else {
        doc.write(`
        if (${id2}.issues.length) {
          payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${k}, ...iss.path] : [${k}]
          })));
        }
        
        if (${id2}.value === undefined) {
          if (${k} in input) {
            newResult[${k}] = undefined;
          }
        } else {
          newResult[${k}] = ${id2}.value;
        }
        
      `);
      }
    }
    doc.write(`payload.value = newResult;`);
    doc.write(`return payload;`);
    const fn = doc.compile();
    return (payload, ctx) => fn(shape, payload, ctx);
  };
  let fastpass;
  const isObject3 = isObject2;
  const jit = !globalConfig.jitless;
  const allowsEval2 = allowsEval;
  const fastEnabled = jit && allowsEval2.value;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value ?? (value = _normalized.value);
    const input = payload.value;
    if (!isObject3(input)) {
      payload.issues.push({
        expected: "object",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
      if (!fastpass)
        fastpass = generateFastpass(def.shape);
      payload = fastpass(payload, ctx);
      if (!catchall)
        return payload;
      return handleCatchall([], input, payload, ctx, value, inst);
    }
    return superParse(payload, ctx);
  };
});
function handleUnionResults(results, final, inst, ctx) {
  for (const result of results) {
    if (result.issues.length === 0) {
      final.value = result.value;
      return final;
    }
  }
  const nonaborted = results.filter((r) => !aborted(r));
  if (nonaborted.length === 1) {
    final.value = nonaborted[0].value;
    return nonaborted[0];
  }
  final.issues.push({
    code: "invalid_union",
    input: final.value,
    inst,
    errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  });
  return final;
}
var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
  defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
  defineLazy(inst._zod, "values", () => {
    if (def.options.every((o) => o._zod.values)) {
      return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
    }
    return void 0;
  });
  defineLazy(inst._zod, "pattern", () => {
    if (def.options.every((o) => o._zod.pattern)) {
      const patterns = def.options.map((o) => o._zod.pattern);
      return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
    }
    return void 0;
  });
  const first = def.options.length === 1 ? def.options[0]._zod.run : null;
  inst._zod.parse = (payload, ctx) => {
    if (first) {
      return first(payload, ctx);
    }
    let async = false;
    const results = [];
    for (const option of def.options) {
      const result = option._zod.run({
        value: payload.value,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        results.push(result);
        async = true;
      } else {
        if (result.issues.length === 0)
          return result;
        results.push(result);
      }
    }
    if (!async)
      return handleUnionResults(results, payload, inst, ctx);
    return Promise.all(results).then((results2) => {
      return handleUnionResults(results2, payload, inst, ctx);
    });
  };
});
function handleExclusiveUnionResults(results, final, inst, ctx) {
  const successes = results.filter((r) => r.issues.length === 0);
  if (successes.length === 1) {
    final.value = successes[0].value;
    return final;
  }
  if (successes.length === 0) {
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
    });
  } else {
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: [],
      inclusive: false
    });
  }
  return final;
}
var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => {
  $ZodUnion.init(inst, def);
  def.inclusive = false;
  const first = def.options.length === 1 ? def.options[0]._zod.run : null;
  inst._zod.parse = (payload, ctx) => {
    if (first) {
      return first(payload, ctx);
    }
    let async = false;
    const results = [];
    for (const option of def.options) {
      const result = option._zod.run({
        value: payload.value,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        results.push(result);
        async = true;
      } else {
        results.push(result);
      }
    }
    if (!async)
      return handleExclusiveUnionResults(results, payload, inst, ctx);
    return Promise.all(results).then((results2) => {
      return handleExclusiveUnionResults(results2, payload, inst, ctx);
    });
  };
});
var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
  def.inclusive = false;
  $ZodUnion.init(inst, def);
  const _super = inst._zod.parse;
  defineLazy(inst._zod, "propValues", () => {
    const propValues = {};
    for (const option of def.options) {
      const pv = option._zod.propValues;
      if (!pv || Object.keys(pv).length === 0)
        throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
      for (const [k, v] of Object.entries(pv)) {
        if (!propValues[k])
          propValues[k] = /* @__PURE__ */ new Set();
        for (const val of v) {
          propValues[k].add(val);
        }
      }
    }
    return propValues;
  });
  const disc = cached(() => {
    const opts = def.options;
    const map4 = /* @__PURE__ */ new Map();
    for (const o of opts) {
      const values = o._zod.propValues?.[def.discriminator];
      if (!values || values.size === 0)
        throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
      for (const v of values) {
        if (map4.has(v)) {
          throw new Error(`Duplicate discriminator value "${String(v)}"`);
        }
        map4.set(v, o);
      }
    }
    return map4;
  });
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!isObject2(input)) {
      payload.issues.push({
        code: "invalid_type",
        expected: "object",
        input,
        inst
      });
      return payload;
    }
    const opt = disc.value.get(input?.[def.discriminator]);
    if (opt) {
      return opt._zod.run(payload, ctx);
    }
    if (def.unionFallback || ctx.direction === "backward") {
      return _super(payload, ctx);
    }
    payload.issues.push({
      code: "invalid_union",
      errors: [],
      note: "No matching discriminator",
      discriminator: def.discriminator,
      options: Array.from(disc.value.keys()),
      input,
      path: [def.discriminator],
      inst
    });
    return payload;
  };
});
var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    const left2 = def.left._zod.run({ value: input, issues: [] }, ctx);
    const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
    const async = left2 instanceof Promise || right2 instanceof Promise;
    if (async) {
      return Promise.all([left2, right2]).then(([left3, right3]) => {
        return handleIntersectionResults(payload, left3, right3);
      });
    }
    return handleIntersectionResults(payload, left2, right2);
  };
});
function mergeValues(a, b) {
  if (a === b) {
    return { valid: true, data: a };
  }
  if (a instanceof Date && b instanceof Date && +a === +b) {
    return { valid: true, data: a };
  }
  if (isPlainObject(a) && isPlainObject(b)) {
    const bKeys = Object.keys(b);
    const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
        };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  }
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) {
      return { valid: false, mergeErrorPath: [] };
    }
    const newArray = [];
    for (let index = 0; index < a.length; index++) {
      const itemA = a[index];
      const itemB = b[index];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
        };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  }
  return { valid: false, mergeErrorPath: [] };
}
function handleIntersectionResults(result, left2, right2) {
  const unrecKeys = /* @__PURE__ */ new Map();
  let unrecIssue;
  for (const iss of left2.issues) {
    if (iss.code === "unrecognized_keys") {
      unrecIssue ?? (unrecIssue = iss);
      for (const k of iss.keys) {
        if (!unrecKeys.has(k))
          unrecKeys.set(k, {});
        unrecKeys.get(k).l = true;
      }
    } else {
      result.issues.push(iss);
    }
  }
  for (const iss of right2.issues) {
    if (iss.code === "unrecognized_keys") {
      for (const k of iss.keys) {
        if (!unrecKeys.has(k))
          unrecKeys.set(k, {});
        unrecKeys.get(k).r = true;
      }
    } else {
      result.issues.push(iss);
    }
  }
  const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
  if (bothKeys.length && unrecIssue) {
    result.issues.push({ ...unrecIssue, keys: bothKeys });
  }
  if (aborted(result))
    return result;
  const merged = mergeValues(left2.value, right2.value);
  if (!merged.valid) {
    throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
  }
  result.value = merged.data;
  return result;
}
var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
  $ZodType.init(inst, def);
  const items = def.items;
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!Array.isArray(input)) {
      payload.issues.push({
        input,
        inst,
        expected: "tuple",
        code: "invalid_type"
      });
      return payload;
    }
    payload.value = [];
    const proms = [];
    const optinStart = getTupleOptStart(items, "optin");
    const optoutStart = getTupleOptStart(items, "optout");
    if (!def.rest) {
      if (input.length < optinStart) {
        payload.issues.push({
          code: "too_small",
          minimum: optinStart,
          inclusive: true,
          input,
          inst,
          origin: "array"
        });
        return payload;
      }
      if (input.length > items.length) {
        payload.issues.push({
          code: "too_big",
          maximum: items.length,
          inclusive: true,
          input,
          inst,
          origin: "array"
        });
      }
    }
    const itemResults = new Array(items.length);
    for (let i = 0; i < items.length; i++) {
      const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);
      if (r instanceof Promise) {
        proms.push(r.then((rr) => {
          itemResults[i] = rr;
        }));
      } else {
        itemResults[i] = r;
      }
    }
    if (def.rest) {
      let i = items.length - 1;
      const rest = input.slice(items.length);
      for (const el of rest) {
        i++;
        const result = def.rest._zod.run({ value: el, issues: [] }, ctx);
        if (result instanceof Promise) {
          proms.push(result.then((r) => handleTupleResult(r, payload, i)));
        } else {
          handleTupleResult(result, payload, i);
        }
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));
    }
    return handleTupleResults(itemResults, payload, items, input, optoutStart);
  };
});
function getTupleOptStart(items, key) {
  for (let i = items.length - 1; i >= 0; i--) {
    if (items[i]._zod[key] !== "optional")
      return i + 1;
  }
  return 0;
}
function handleTupleResult(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}
function handleTupleResults(itemResults, final, items, input, optoutStart) {
  for (let i = 0; i < items.length; i++) {
    const r = itemResults[i];
    const isPresent = i < input.length;
    if (r.issues.length) {
      if (!isPresent && i >= optoutStart) {
        final.value.length = i;
        break;
      }
      final.issues.push(...prefixIssues(i, r.issues));
    }
    final.value[i] = r.value;
  }
  for (let i = final.value.length - 1; i >= input.length; i--) {
    if (items[i]._zod.optout === "optional" && final.value[i] === void 0) {
      final.value.length = i;
    } else {
      break;
    }
  }
  return final;
}
var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!isPlainObject(input)) {
      payload.issues.push({
        expected: "record",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    const proms = [];
    const values = def.keyType._zod.values;
    if (values) {
      payload.value = {};
      const recordKeys = /* @__PURE__ */ new Set();
      for (const key of values) {
        if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
          recordKeys.add(typeof key === "number" ? key.toString() : key);
          const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
          if (keyResult instanceof Promise) {
            throw new Error("Async schemas not supported in object keys currently");
          }
          if (keyResult.issues.length) {
            payload.issues.push({
              code: "invalid_key",
              origin: "record",
              issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
              input: key,
              path: [key],
              inst
            });
            continue;
          }
          const outKey = keyResult.value;
          const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => {
              if (result2.issues.length) {
                payload.issues.push(...prefixIssues(key, result2.issues));
              }
              payload.value[outKey] = result2.value;
            }));
          } else {
            if (result.issues.length) {
              payload.issues.push(...prefixIssues(key, result.issues));
            }
            payload.value[outKey] = result.value;
          }
        }
      }
      let unrecognized;
      for (const key in input) {
        if (!recordKeys.has(key)) {
          unrecognized = unrecognized ?? [];
          unrecognized.push(key);
        }
      }
      if (unrecognized && unrecognized.length > 0) {
        payload.issues.push({
          code: "unrecognized_keys",
          input,
          inst,
          keys: unrecognized
        });
      }
    } else {
      payload.value = {};
      for (const key of Reflect.ownKeys(input)) {
        if (key === "__proto__")
          continue;
        if (!Object.prototype.propertyIsEnumerable.call(input, key))
          continue;
        let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
        if (keyResult instanceof Promise) {
          throw new Error("Async schemas not supported in object keys currently");
        }
        const checkNumericKey = typeof key === "string" && number5.test(key) && keyResult.issues.length;
        if (checkNumericKey) {
          const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);
          if (retryResult instanceof Promise) {
            throw new Error("Async schemas not supported in object keys currently");
          }
          if (retryResult.issues.length === 0) {
            keyResult = retryResult;
          }
        }
        if (keyResult.issues.length) {
          if (def.mode === "loose") {
            payload.value[key] = input[key];
          } else {
            payload.issues.push({
              code: "invalid_key",
              origin: "record",
              issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
              input: key,
              path: [key],
              inst
            });
          }
          continue;
        }
        const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
        if (result instanceof Promise) {
          proms.push(result.then((result2) => {
            if (result2.issues.length) {
              payload.issues.push(...prefixIssues(key, result2.issues));
            }
            payload.value[keyResult.value] = result2.value;
          }));
        } else {
          if (result.issues.length) {
            payload.issues.push(...prefixIssues(key, result.issues));
          }
          payload.value[keyResult.value] = result.value;
        }
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!(input instanceof Map)) {
      payload.issues.push({
        expected: "map",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    const proms = [];
    payload.value = /* @__PURE__ */ new Map();
    for (const [key, value] of input) {
      const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
      const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx);
      if (keyResult instanceof Promise || valueResult instanceof Promise) {
        proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => {
          handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx);
        }));
      } else {
        handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
      }
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
  if (keyResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, keyResult.issues));
    } else {
      final.issues.push({
        code: "invalid_key",
        origin: "map",
        input,
        inst,
        issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  if (valueResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, valueResult.issues));
    } else {
      final.issues.push({
        origin: "map",
        code: "invalid_element",
        input,
        inst,
        key,
        issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  final.value.set(keyResult.value, valueResult.value);
}
var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!(input instanceof Set)) {
      payload.issues.push({
        input,
        inst,
        expected: "set",
        code: "invalid_type"
      });
      return payload;
    }
    const proms = [];
    payload.value = /* @__PURE__ */ new Set();
    for (const item of input) {
      const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleSetResult(result2, payload)));
      } else
        handleSetResult(result, payload);
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleSetResult(result, final) {
  if (result.issues.length) {
    final.issues.push(...result.issues);
  }
  final.value.add(result.value);
}
var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
  $ZodType.init(inst, def);
  const values = getEnumValues(def.entries);
  const valuesSet = new Set(values);
  inst._zod.values = valuesSet;
  inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (valuesSet.has(input)) {
      return payload;
    }
    payload.issues.push({
      code: "invalid_value",
      values,
      input,
      inst
    });
    return payload;
  };
});
var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
  $ZodType.init(inst, def);
  if (def.values.length === 0) {
    throw new Error("Cannot create literal schema with no valid values");
  }
  const values = new Set(def.values);
  inst._zod.values = values;
  inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (values.has(input)) {
      return payload;
    }
    payload.issues.push({
      code: "invalid_value",
      values: def.values,
      input,
      inst
    });
    return payload;
  };
});
var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (input instanceof File)
      return payload;
    payload.issues.push({
      expected: "file",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      throw new $ZodEncodeError(inst.constructor.name);
    }
    const _out = def.transform(payload.value, payload);
    if (ctx.async) {
      const output = _out instanceof Promise ? _out : Promise.resolve(_out);
      return output.then((output2) => {
        payload.value = output2;
        payload.fallback = true;
        return payload;
      });
    }
    if (_out instanceof Promise) {
      throw new $ZodAsyncError();
    }
    payload.value = _out;
    payload.fallback = true;
    return payload;
  };
});
function handleOptionalResult(result, input) {
  if (input === void 0 && (result.issues.length || result.fallback)) {
    return { issues: [], value: void 0 };
  }
  return result;
}
var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  inst._zod.optout = "optional";
  defineLazy(inst._zod, "values", () => {
    return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
  });
  defineLazy(inst._zod, "pattern", () => {
    const pattern = def.innerType._zod.pattern;
    return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    if (def.innerType._zod.optin === "optional") {
      const input = payload.value;
      const result = def.innerType._zod.run(payload, ctx);
      if (result instanceof Promise)
        return result.then((r) => handleOptionalResult(r, input));
      return handleOptionalResult(result, input);
    }
    if (payload.value === void 0) {
      return payload;
    }
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
  $ZodOptional.init(inst, def);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
  inst._zod.parse = (payload, ctx) => {
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy(inst._zod, "pattern", () => {
    const pattern = def.innerType._zod.pattern;
    return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
  });
  defineLazy(inst._zod, "values", () => {
    return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    if (payload.value === null)
      return payload;
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    if (payload.value === void 0) {
      payload.value = def.defaultValue;
      return payload;
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => handleDefaultResult(result2, def));
    }
    return handleDefaultResult(result, def);
  };
});
function handleDefaultResult(payload, def) {
  if (payload.value === void 0) {
    payload.value = def.defaultValue;
  }
  return payload;
}
var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    if (payload.value === void 0) {
      payload.value = def.defaultValue;
    }
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => {
    const v = def.innerType._zod.values;
    return v ? new Set([...v].filter((x2) => x2 !== void 0)) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => handleNonOptionalResult(result2, inst));
    }
    return handleNonOptionalResult(result, inst);
  };
});
function handleNonOptionalResult(payload, inst) {
  if (!payload.issues.length && payload.value === void 0) {
    payload.issues.push({
      code: "invalid_type",
      expected: "nonoptional",
      input: payload.value,
      inst
    });
  }
  return payload;
}
var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      throw new $ZodEncodeError("ZodSuccess");
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => {
        payload.value = result2.issues.length === 0;
        return payload;
      });
    }
    payload.value = result.issues.length === 0;
    return payload;
  };
});
var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => {
        payload.value = result2.value;
        if (result2.issues.length) {
          payload.value = def.catchValue({
            ...payload,
            error: {
              issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
            },
            input: payload.value
          });
          payload.issues = [];
          payload.fallback = true;
        }
        return payload;
      });
    }
    payload.value = result.value;
    if (result.issues.length) {
      payload.value = def.catchValue({
        ...payload,
        error: {
          issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
        },
        input: payload.value
      });
      payload.issues = [];
      payload.fallback = true;
    }
    return payload;
  };
});
var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
      payload.issues.push({
        input: payload.value,
        inst,
        expected: "nan",
        code: "invalid_type"
      });
      return payload;
    }
    return payload;
  };
});
var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => def.in._zod.values);
  defineLazy(inst._zod, "optin", () => def.in._zod.optin);
  defineLazy(inst._zod, "optout", () => def.out._zod.optout);
  defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      const right2 = def.out._zod.run(payload, ctx);
      if (right2 instanceof Promise) {
        return right2.then((right3) => handlePipeResult(right3, def.in, ctx));
      }
      return handlePipeResult(right2, def.in, ctx);
    }
    const left2 = def.in._zod.run(payload, ctx);
    if (left2 instanceof Promise) {
      return left2.then((left3) => handlePipeResult(left3, def.out, ctx));
    }
    return handlePipeResult(left2, def.out, ctx);
  };
});
function handlePipeResult(left2, next, ctx) {
  if (left2.issues.length) {
    left2.aborted = true;
    return left2;
  }
  return next._zod.run({ value: left2.value, issues: left2.issues, fallback: left2.fallback }, ctx);
}
var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => def.in._zod.values);
  defineLazy(inst._zod, "optin", () => def.in._zod.optin);
  defineLazy(inst._zod, "optout", () => def.out._zod.optout);
  defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
  inst._zod.parse = (payload, ctx) => {
    const direction = ctx.direction || "forward";
    if (direction === "forward") {
      const left2 = def.in._zod.run(payload, ctx);
      if (left2 instanceof Promise) {
        return left2.then((left3) => handleCodecAResult(left3, def, ctx));
      }
      return handleCodecAResult(left2, def, ctx);
    } else {
      const right2 = def.out._zod.run(payload, ctx);
      if (right2 instanceof Promise) {
        return right2.then((right3) => handleCodecAResult(right3, def, ctx));
      }
      return handleCodecAResult(right2, def, ctx);
    }
  };
});
function handleCodecAResult(result, def, ctx) {
  if (result.issues.length) {
    result.aborted = true;
    return result;
  }
  const direction = ctx.direction || "forward";
  if (direction === "forward") {
    const transformed = def.transform(result.value, result);
    if (transformed instanceof Promise) {
      return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));
    }
    return handleCodecTxResult(result, transformed, def.out, ctx);
  } else {
    const transformed = def.reverseTransform(result.value, result);
    if (transformed instanceof Promise) {
      return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));
    }
    return handleCodecTxResult(result, transformed, def.in, ctx);
  }
}
function handleCodecTxResult(left2, value, nextSchema, ctx) {
  if (left2.issues.length) {
    left2.aborted = true;
    return left2;
  }
  return nextSchema._zod.run({ value, issues: left2.issues }, ctx);
}
var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) => {
  $ZodPipe.init(inst, def);
});
var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
  defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then(handleReadonlyResult);
    }
    return handleReadonlyResult(result);
  };
});
function handleReadonlyResult(payload) {
  payload.value = Object.freeze(payload.value);
  return payload;
}
var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => {
  $ZodType.init(inst, def);
  const regexParts = [];
  for (const part of def.parts) {
    if (typeof part === "object" && part !== null) {
      if (!part._zod.pattern) {
        throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
      }
      const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
      if (!source)
        throw new Error(`Invalid template literal part: ${part._zod.traits}`);
      const start2 = source.startsWith("^") ? 1 : 0;
      const end = source.endsWith("$") ? source.length - 1 : source.length;
      regexParts.push(source.slice(start2, end));
    } else if (part === null || primitiveTypes.has(typeof part)) {
      regexParts.push(escapeRegex(`${part}`));
    } else {
      throw new Error(`Invalid template literal part: ${part}`);
    }
  }
  inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "string") {
      payload.issues.push({
        input: payload.value,
        inst,
        expected: "string",
        code: "invalid_type"
      });
      return payload;
    }
    inst._zod.pattern.lastIndex = 0;
    if (!inst._zod.pattern.test(payload.value)) {
      payload.issues.push({
        input: payload.value,
        inst,
        code: "invalid_format",
        format: def.format ?? "template_literal",
        pattern: inst._zod.pattern.source
      });
      return payload;
    }
    return payload;
  };
});
var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => {
  $ZodType.init(inst, def);
  inst._def = def;
  inst._zod.def = def;
  inst.implement = (func) => {
    if (typeof func !== "function") {
      throw new Error("implement() must be called with a function");
    }
    return function(...args) {
      const parsedArgs = inst._def.input ? parse3(inst._def.input, args) : args;
      const result = Reflect.apply(func, this, parsedArgs);
      if (inst._def.output) {
        return parse3(inst._def.output, result);
      }
      return result;
    };
  };
  inst.implementAsync = (func) => {
    if (typeof func !== "function") {
      throw new Error("implementAsync() must be called with a function");
    }
    return async function(...args) {
      const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;
      const result = await Reflect.apply(func, this, parsedArgs);
      if (inst._def.output) {
        return await parseAsync(inst._def.output, result);
      }
      return result;
    };
  };
  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "function") {
      payload.issues.push({
        code: "invalid_type",
        expected: "function",
        input: payload.value,
        inst
      });
      return payload;
    }
    const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise";
    if (hasPromiseOutput) {
      payload.value = inst.implementAsync(payload.value);
    } else {
      payload.value = inst.implement(payload.value);
    }
    return payload;
  };
  inst.input = (...args) => {
    const F = inst.constructor;
    if (Array.isArray(args[0])) {
      return new F({
        type: "function",
        input: new $ZodTuple({
          type: "tuple",
          items: args[0],
          rest: args[1]
        }),
        output: inst._def.output
      });
    }
    return new F({
      type: "function",
      input: args[0],
      output: inst._def.output
    });
  };
  inst.output = (output) => {
    const F = inst.constructor;
    return new F({
      type: "function",
      input: inst._def.input,
      output
    });
  };
  return inst;
});
var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
  };
});
var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "innerType", () => {
    const d = def;
    if (!d._cachedInner)
      d._cachedInner = def.getter();
    return d._cachedInner;
  });
  defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern);
  defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues);
  defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0);
  defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0);
  inst._zod.parse = (payload, ctx) => {
    const inner = inst._zod.innerType;
    return inner._zod.run(payload, ctx);
  };
});
var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
  $ZodCheck.init(inst, def);
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _) => {
    return payload;
  };
  inst._zod.check = (payload) => {
    const input = payload.value;
    const r = def.fn(input);
    if (r instanceof Promise) {
      return r.then((r2) => handleRefineResult(r2, payload, input, inst));
    }
    handleRefineResult(r, payload, input, inst);
    return;
  };
});
function handleRefineResult(result, payload, input, inst) {
  if (!result) {
    const _iss = {
      code: "custom",
      input,
      inst,
      // incorporates params.error into issue reporting
      path: [...inst._zod.def.path ?? []],
      // incorporates params.error into issue reporting
      continue: !inst._zod.def.abort
      // params: inst._zod.def.params,
    };
    if (inst._zod.def.params)
      _iss.params = inst._zod.def.params;
    payload.issues.push(issue(_iss));
  }
}

// node_modules/zod/v4/locales/index.js
var locales_exports = {};
__export(locales_exports, {
  ar: () => ar_default,
  az: () => az_default,
  be: () => be_default,
  bg: () => bg_default,
  ca: () => ca_default,
  cs: () => cs_default,
  da: () => da_default,
  de: () => de_default,
  el: () => el_default,
  en: () => en_default,
  eo: () => eo_default,
  es: () => es_default,
  fa: () => fa_default,
  fi: () => fi_default,
  fr: () => fr_default,
  frCA: () => fr_CA_default,
  he: () => he_default,
  hr: () => hr_default,
  hu: () => hu_default,
  hy: () => hy_default,
  id: () => id_default,
  is: () => is_default,
  it: () => it_default,
  ja: () => ja_default,
  ka: () => ka_default,
  kh: () => kh_default,
  km: () => km_default,
  ko: () => ko_default,
  lt: () => lt_default,
  mk: () => mk_default,
  ms: () => ms_default,
  nl: () => nl_default,
  no: () => no_default,
  ota: () => ota_default,
  pl: () => pl_default,
  ps: () => ps_default,
  pt: () => pt_default,
  ro: () => ro_default,
  ru: () => ru_default,
  sl: () => sl_default,
  sv: () => sv_default,
  ta: () => ta_default,
  th: () => th_default,
  tr: () => tr_default,
  ua: () => ua_default,
  uk: () => uk_default,
  ur: () => ur_default,
  uz: () => uz_default,
  vi: () => vi_default,
  yo: () => yo_default,
  zhCN: () => zh_CN_default,
  zhTW: () => zh_TW_default
});

// node_modules/zod/v4/locales/ar.js
var error = () => {
  const Sizable = {
    string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
    file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
    array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
    set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0645\u062F\u062E\u0644",
    email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",
    url: "\u0631\u0627\u0628\u0637",
    emoji: "\u0625\u064A\u0645\u0648\u062C\u064A",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4",
    ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6",
    cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",
    cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",
    base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",
    base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",
    json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",
    e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",
    jwt: "JWT",
    template_literal: "\u0645\u062F\u062E\u0644"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;
        }
        return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`;
        return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`;
        return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`;
      }
      case "not_multiple_of":
        return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
      case "invalid_key":
        return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
      case "invalid_union":
        return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
      case "invalid_element":
        return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
      default:
        return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
    }
  };
};
function ar_default() {
  return {
    localeError: error()
  };
}

// node_modules/zod/v4/locales/az.js
var error2 = () => {
  const Sizable = {
    string: { unit: "simvol", verb: "olmal\u0131d\u0131r" },
    file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
    array: { unit: "element", verb: "olmal\u0131d\u0131r" },
    set: { unit: "element", verb: "olmal\u0131d\u0131r" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "email address",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datetime",
    date: "ISO date",
    time: "ISO time",
    duration: "ISO duration",
    ipv4: "IPv4 address",
    ipv6: "IPv6 address",
    cidrv4: "IPv4 range",
    cidrv6: "IPv6 range",
    base64: "base64-encoded string",
    base64url: "base64url-encoded string",
    json_string: "JSON string",
    e164: "E.164 number",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`;
        }
        return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`;
        return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
        return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;
        if (_issue.format === "ends_with")
          return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`;
        if (_issue.format === "includes")
          return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`;
        if (_issue.format === "regex")
          return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;
        return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;
      case "invalid_union":
        return "Yanl\u0131\u015F d\u0259y\u0259r";
      case "invalid_element":
        return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;
      default:
        return `Yanl\u0131\u015F d\u0259y\u0259r`;
    }
  };
};
function az_default() {
  return {
    localeError: error2()
  };
}

// node_modules/zod/v4/locales/be.js
function getBelarusianPlural(count, one2, few, many) {
  const absCount = Math.abs(count);
  const lastDigit = absCount % 10;
  const lastTwoDigits = absCount % 100;
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
    return many;
  }
  if (lastDigit === 1) {
    return one2;
  }
  if (lastDigit >= 2 && lastDigit <= 4) {
    return few;
  }
  return many;
}
var error3 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "\u0441\u0456\u043C\u0432\u0430\u043B",
        few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B",
        many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"
      },
      verb: "\u043C\u0435\u0446\u044C"
    },
    array: {
      unit: {
        one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
        few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
        many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
      },
      verb: "\u043C\u0435\u0446\u044C"
    },
    set: {
      unit: {
        one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
        few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
        many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
      },
      verb: "\u043C\u0435\u0446\u044C"
    },
    file: {
      unit: {
        one: "\u0431\u0430\u0439\u0442",
        few: "\u0431\u0430\u0439\u0442\u044B",
        many: "\u0431\u0430\u0439\u0442\u0430\u045E"
      },
      verb: "\u043C\u0435\u0446\u044C"
    }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0443\u0432\u043E\u0434",
    email: "email \u0430\u0434\u0440\u0430\u0441",
    url: "URL",
    emoji: "\u044D\u043C\u043E\u0434\u0437\u0456",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",
    date: "ISO \u0434\u0430\u0442\u0430",
    time: "ISO \u0447\u0430\u0441",
    duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",
    ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441",
    ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441",
    cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
    cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
    base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",
    base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",
    json_string: "JSON \u0440\u0430\u0434\u043E\u043A",
    e164: "\u043D\u0443\u043C\u0430\u0440 E.164",
    jwt: "JWT",
    template_literal: "\u0443\u0432\u043E\u0434"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u043B\u0456\u043A",
    array: "\u043C\u0430\u0441\u0456\u045E"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`;
        }
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const maxValue = Number(issue2.maximum);
          const unit3 = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit3}`;
        }
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const minValue = Number(issue2.minimum);
          const unit3 = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit3}`;
        }
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
      case "invalid_union":
        return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";
      case "invalid_element":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`;
      default:
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`;
    }
  };
};
function be_default() {
  return {
    localeError: error3()
  };
}

// node_modules/zod/v4/locales/bg.js
var error4 = () => {
  const Sizable = {
    string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" },
    file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" },
    array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" },
    set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0432\u0445\u043E\u0434",
    email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",
    url: "URL",
    emoji: "\u0435\u043C\u043E\u0434\u0436\u0438",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0432\u0440\u0435\u043C\u0435",
    date: "ISO \u0434\u0430\u0442\u0430",
    time: "ISO \u0432\u0440\u0435\u043C\u0435",
    duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",
    ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441",
    ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441",
    cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
    cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
    base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",
    base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",
    json_string: "JSON \u043D\u0438\u0437",
    e164: "E.164 \u043D\u043E\u043C\u0435\u0440",
    jwt: "JWT",
    template_literal: "\u0432\u0445\u043E\u0434"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0447\u0438\u0441\u043B\u043E",
    array: "\u043C\u0430\u0441\u0438\u0432"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;
        }
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`;
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`;
        return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`;
        let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";
        if (_issue.format === "emoji")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
        if (_issue.format === "datetime")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
        if (_issue.format === "date")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";
        if (_issue.format === "time")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
        if (_issue.format === "duration")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";
        return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;
      case "invalid_union":
        return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";
      case "invalid_element":
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`;
      default:
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`;
    }
  };
};
function bg_default() {
  return {
    localeError: error4()
  };
}

// node_modules/zod/v4/locales/ca.js
var error5 = () => {
  const Sizable = {
    string: { unit: "car\xE0cters", verb: "contenir" },
    file: { unit: "bytes", verb: "contenir" },
    array: { unit: "elements", verb: "contenir" },
    set: { unit: "elements", verb: "contenir" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "entrada",
    email: "adre\xE7a electr\xF2nica",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "data i hora ISO",
    date: "data ISO",
    time: "hora ISO",
    duration: "durada ISO",
    ipv4: "adre\xE7a IPv4",
    ipv6: "adre\xE7a IPv6",
    cidrv4: "rang IPv4",
    cidrv6: "rang IPv6",
    base64: "cadena codificada en base64",
    base64url: "cadena codificada en base64url",
    json_string: "cadena JSON",
    e164: "n\xFAmero E.164",
    jwt: "JWT",
    template_literal: "entrada"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`;
        }
        return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;
        return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
        return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`;
        return `Format inv\xE0lid per a ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Clau inv\xE0lida a ${issue2.origin}`;
      case "invalid_union":
        return "Entrada inv\xE0lida";
      // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general
      case "invalid_element":
        return `Element inv\xE0lid a ${issue2.origin}`;
      default:
        return `Entrada inv\xE0lida`;
    }
  };
};
function ca_default() {
  return {
    localeError: error5()
  };
}

// node_modules/zod/v4/locales/cs.js
var error6 = () => {
  const Sizable = {
    string: { unit: "znak\u016F", verb: "m\xEDt" },
    file: { unit: "bajt\u016F", verb: "m\xEDt" },
    array: { unit: "prvk\u016F", verb: "m\xEDt" },
    set: { unit: "prvk\u016F", verb: "m\xEDt" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "regul\xE1rn\xED v\xFDraz",
    email: "e-mailov\xE1 adresa",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "datum a \u010Das ve form\xE1tu ISO",
    date: "datum ve form\xE1tu ISO",
    time: "\u010Das ve form\xE1tu ISO",
    duration: "doba trv\xE1n\xED ISO",
    ipv4: "IPv4 adresa",
    ipv6: "IPv6 adresa",
    cidrv4: "rozsah IPv4",
    cidrv6: "rozsah IPv6",
    base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",
    base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",
    json_string: "\u0159et\u011Bzec ve form\xE1tu JSON",
    e164: "\u010D\xEDslo E.164",
    jwt: "JWT",
    template_literal: "vstup"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u010D\xEDslo",
    string: "\u0159et\u011Bzec",
    function: "funkce",
    array: "pole"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`;
        }
        return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`;
        return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
        }
        return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
        }
        return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`;
        return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`;
      case "invalid_union":
        return "Neplatn\xFD vstup";
      case "invalid_element":
        return `Neplatn\xE1 hodnota v ${issue2.origin}`;
      default:
        return `Neplatn\xFD vstup`;
    }
  };
};
function cs_default() {
  return {
    localeError: error6()
  };
}

// node_modules/zod/v4/locales/da.js
var error7 = () => {
  const Sizable = {
    string: { unit: "tegn", verb: "havde" },
    file: { unit: "bytes", verb: "havde" },
    array: { unit: "elementer", verb: "indeholdt" },
    set: { unit: "elementer", verb: "indeholdt" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "e-mailadresse",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO dato- og klokkesl\xE6t",
    date: "ISO-dato",
    time: "ISO-klokkesl\xE6t",
    duration: "ISO-varighed",
    ipv4: "IPv4-omr\xE5de",
    ipv6: "IPv6-omr\xE5de",
    cidrv4: "IPv4-spektrum",
    cidrv6: "IPv6-spektrum",
    base64: "base64-kodet streng",
    base64url: "base64url-kodet streng",
    json_string: "JSON-streng",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "streng",
    number: "tal",
    boolean: "boolean",
    array: "liste",
    object: "objekt",
    set: "s\xE6t",
    file: "fil"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`;
        }
        return `Ugyldigt input: forventede ${expected}, fik ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`;
        return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing)
          return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`;
        return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing) {
          return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ugyldig streng: skal starte med "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Ugyldig streng: skal ende med "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ugyldig streng: skal indeholde "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`;
        return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig n\xF8gle i ${issue2.origin}`;
      case "invalid_union":
        return "Ugyldigt input: matcher ingen af de tilladte typer";
      case "invalid_element":
        return `Ugyldig v\xE6rdi i ${issue2.origin}`;
      default:
        return `Ugyldigt input`;
    }
  };
};
function da_default() {
  return {
    localeError: error7()
  };
}

// node_modules/zod/v4/locales/de.js
var error8 = () => {
  const Sizable = {
    string: { unit: "Zeichen", verb: "zu haben" },
    file: { unit: "Bytes", verb: "zu haben" },
    array: { unit: "Elemente", verb: "zu haben" },
    set: { unit: "Elemente", verb: "zu haben" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "Eingabe",
    email: "E-Mail-Adresse",
    url: "URL",
    emoji: "Emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO-Datum und -Uhrzeit",
    date: "ISO-Datum",
    time: "ISO-Uhrzeit",
    duration: "ISO-Dauer",
    ipv4: "IPv4-Adresse",
    ipv6: "IPv6-Adresse",
    cidrv4: "IPv4-Bereich",
    cidrv6: "IPv6-Bereich",
    base64: "Base64-codierter String",
    base64url: "Base64-URL-codierter String",
    json_string: "JSON-String",
    e164: "E.164-Nummer",
    jwt: "JWT",
    template_literal: "Eingabe"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "Zahl",
    array: "Array"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`;
        }
        return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;
        return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`;
        return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`;
        }
        return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`;
        if (_issue.format === "ends_with")
          return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`;
        if (_issue.format === "includes")
          return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`;
        if (_issue.format === "regex")
          return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`;
        return `Ung\xFCltig: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`;
      case "invalid_union":
        return "Ung\xFCltige Eingabe";
      case "invalid_element":
        return `Ung\xFCltiger Wert in ${issue2.origin}`;
      default:
        return `Ung\xFCltige Eingabe`;
    }
  };
};
function de_default() {
  return {
    localeError: error8()
  };
}

// node_modules/zod/v4/locales/el.js
var error9 = () => {
  const Sizable = {
    string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
    file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
    array: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
    set: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
    map: { unit: "\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",
    email: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",
    date: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",
    time: "ISO \u03CE\u03C1\u03B1",
    duration: "ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",
    ipv4: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",
    ipv6: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",
    mac: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",
    cidrv4: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",
    cidrv6: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",
    base64: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",
    base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",
    json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",
    e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",
    jwt: "JWT",
    template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (typeof issue2.expected === "string" && /^[A-Z]/.test(issue2.expected)) {
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${issue2.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`;
        }
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${stringifyPrimitive(issue2.values[0])}`;
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`;
        return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${_issue.pattern}`;
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${issue2.keys.length > 1 ? "\u03B1" : "\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${issue2.keys.length > 1 ? "\u03B9\u03AC" : "\u03AF"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${issue2.origin}`;
      case "invalid_union":
        return "\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";
      case "invalid_element":
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${issue2.origin}`;
      default:
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2`;
    }
  };
};
function el_default() {
  return {
    localeError: error9()
  };
}

// node_modules/zod/v4/locales/en.js
var error10 = () => {
  const Sizable = {
    string: { unit: "characters", verb: "to have" },
    file: { unit: "bytes", verb: "to have" },
    array: { unit: "items", verb: "to have" },
    set: { unit: "items", verb: "to have" },
    map: { unit: "entries", verb: "to have" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "email address",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datetime",
    date: "ISO date",
    time: "ISO time",
    duration: "ISO duration",
    ipv4: "IPv4 address",
    ipv6: "IPv6 address",
    mac: "MAC address",
    cidrv4: "IPv4 range",
    cidrv6: "IPv6 range",
    base64: "base64-encoded string",
    base64url: "base64url-encoded string",
    json_string: "JSON string",
    e164: "E.164 number",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    // Compatibility: "nan" -> "NaN" for display
    nan: "NaN"
    // All other type names omitted - they fall back to raw values via ?? operator
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        return `Invalid input: expected ${expected}, received ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
        return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
        return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Invalid string: must start with "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Invalid string: must end with "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Invalid string: must include "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Invalid string: must match pattern ${_issue.pattern}`;
        return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Invalid number: must be a multiple of ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Invalid key in ${issue2.origin}`;
      case "invalid_union":
        if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) {
          const opts = issue2.options.map((o) => `'${o}'`).join(" | ");
          return `Invalid discriminator value. Expected ${opts}`;
        }
        return "Invalid input";
      case "invalid_element":
        return `Invalid value in ${issue2.origin}`;
      default:
        return `Invalid input`;
    }
  };
};
function en_default() {
  return {
    localeError: error10()
  };
}

// node_modules/zod/v4/locales/eo.js
var error11 = () => {
  const Sizable = {
    string: { unit: "karaktrojn", verb: "havi" },
    file: { unit: "bajtojn", verb: "havi" },
    array: { unit: "elementojn", verb: "havi" },
    set: { unit: "elementojn", verb: "havi" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "enigo",
    email: "retadreso",
    url: "URL",
    emoji: "emo\u011Dio",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO-datotempo",
    date: "ISO-dato",
    time: "ISO-tempo",
    duration: "ISO-da\u016Dro",
    ipv4: "IPv4-adreso",
    ipv6: "IPv6-adreso",
    cidrv4: "IPv4-rango",
    cidrv6: "IPv6-rango",
    base64: "64-ume kodita karaktraro",
    base64url: "URL-64-ume kodita karaktraro",
    json_string: "JSON-karaktraro",
    e164: "E.164-nombro",
    jwt: "JWT",
    template_literal: "enigo"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "nombro",
    array: "tabelo",
    null: "senvalora"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`;
        }
        return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`;
        return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`;
        return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;
        return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Nevalida \u015Dlosilo en ${issue2.origin}`;
      case "invalid_union":
        return "Nevalida enigo";
      case "invalid_element":
        return `Nevalida valoro en ${issue2.origin}`;
      default:
        return `Nevalida enigo`;
    }
  };
};
function eo_default() {
  return {
    localeError: error11()
  };
}

// node_modules/zod/v4/locales/es.js
var error12 = () => {
  const Sizable = {
    string: { unit: "caracteres", verb: "tener" },
    file: { unit: "bytes", verb: "tener" },
    array: { unit: "elementos", verb: "tener" },
    set: { unit: "elementos", verb: "tener" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "entrada",
    email: "direcci\xF3n de correo electr\xF3nico",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "fecha y hora ISO",
    date: "fecha ISO",
    time: "hora ISO",
    duration: "duraci\xF3n ISO",
    ipv4: "direcci\xF3n IPv4",
    ipv6: "direcci\xF3n IPv6",
    cidrv4: "rango IPv4",
    cidrv6: "rango IPv6",
    base64: "cadena codificada en base64",
    base64url: "URL codificada en base64",
    json_string: "cadena JSON",
    e164: "n\xFAmero E.164",
    jwt: "JWT",
    template_literal: "entrada"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "texto",
    number: "n\xFAmero",
    boolean: "booleano",
    array: "arreglo",
    object: "objeto",
    set: "conjunto",
    file: "archivo",
    date: "fecha",
    bigint: "n\xFAmero grande",
    symbol: "s\xEDmbolo",
    undefined: "indefinido",
    null: "nulo",
    function: "funci\xF3n",
    map: "mapa",
    record: "registro",
    tuple: "tupla",
    enum: "enumeraci\xF3n",
    union: "uni\xF3n",
    literal: "literal",
    promise: "promesa",
    void: "vac\xEDo",
    never: "nunca",
    unknown: "desconocido",
    any: "cualquiera"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`;
        }
        return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;
        return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing)
          return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
        return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing) {
          return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`;
        return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Llave inv\xE1lida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
      case "invalid_union":
        return "Entrada inv\xE1lida";
      case "invalid_element":
        return `Valor inv\xE1lido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
      default:
        return `Entrada inv\xE1lida`;
    }
  };
};
function es_default() {
  return {
    localeError: error12()
  };
}

// node_modules/zod/v4/locales/fa.js
var error13 = () => {
  const Sizable = {
    string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
    file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
    array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
    set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0648\u0631\u0648\u062F\u06CC",
    email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",
    url: "URL",
    emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
    date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",
    time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
    duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
    ipv4: "IPv4 \u0622\u062F\u0631\u0633",
    ipv6: "IPv6 \u0622\u062F\u0631\u0633",
    cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647",
    cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647",
    base64: "base64-encoded \u0631\u0634\u062A\u0647",
    base64url: "base64url-encoded \u0631\u0634\u062A\u0647",
    json_string: "JSON \u0631\u0634\u062A\u0647",
    e164: "E.164 \u0639\u062F\u062F",
    jwt: "JWT",
    template_literal: "\u0648\u0631\u0648\u062F\u06CC"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0639\u062F\u062F",
    array: "\u0622\u0631\u0627\u06CC\u0647"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;
        }
        return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;
      }
      case "invalid_value":
        if (issue2.values.length === 1) {
          return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;
        }
        return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;
        }
        return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`;
        }
        return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;
        }
        if (_issue.format === "ends_with") {
          return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;
        }
        if (_issue.format === "includes") {
          return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`;
        }
        if (_issue.format === "regex") {
          return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;
        }
        return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
      }
      case "not_multiple_of":
        return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`;
      case "unrecognized_keys":
        return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`;
      case "invalid_union":
        return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
      case "invalid_element":
        return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`;
      default:
        return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
    }
  };
};
function fa_default() {
  return {
    localeError: error13()
  };
}

// node_modules/zod/v4/locales/fi.js
var error14 = () => {
  const Sizable = {
    string: { unit: "merkki\xE4", subject: "merkkijonon" },
    file: { unit: "tavua", subject: "tiedoston" },
    array: { unit: "alkiota", subject: "listan" },
    set: { unit: "alkiota", subject: "joukon" },
    number: { unit: "", subject: "luvun" },
    bigint: { unit: "", subject: "suuren kokonaisluvun" },
    int: { unit: "", subject: "kokonaisluvun" },
    date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "s\xE4\xE4nn\xF6llinen lauseke",
    email: "s\xE4hk\xF6postiosoite",
    url: "URL-osoite",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO-aikaleima",
    date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",
    time: "ISO-aika",
    duration: "ISO-kesto",
    ipv4: "IPv4-osoite",
    ipv6: "IPv6-osoite",
    cidrv4: "IPv4-alue",
    cidrv6: "IPv6-alue",
    base64: "base64-koodattu merkkijono",
    base64url: "base64url-koodattu merkkijono",
    json_string: "JSON-merkkijono",
    e164: "E.164-luku",
    jwt: "JWT",
    template_literal: "templaattimerkkijono"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`;
        }
        return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`;
        return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim();
        }
        return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim();
        }
        return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`;
        if (_issue.format === "regex") {
          return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`;
        }
        return `Virheellinen ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return "Virheellinen avain tietueessa";
      case "invalid_union":
        return "Virheellinen unioni";
      case "invalid_element":
        return "Virheellinen arvo joukossa";
      default:
        return `Virheellinen sy\xF6te`;
    }
  };
};
function fi_default() {
  return {
    localeError: error14()
  };
}

// node_modules/zod/v4/locales/fr.js
var error15 = () => {
  const Sizable = {
    string: { unit: "caract\xE8res", verb: "avoir" },
    file: { unit: "octets", verb: "avoir" },
    array: { unit: "\xE9l\xE9ments", verb: "avoir" },
    set: { unit: "\xE9l\xE9ments", verb: "avoir" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "entr\xE9e",
    email: "adresse e-mail",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "date et heure ISO",
    date: "date ISO",
    time: "heure ISO",
    duration: "dur\xE9e ISO",
    ipv4: "adresse IPv4",
    ipv6: "adresse IPv6",
    cidrv4: "plage IPv4",
    cidrv6: "plage IPv6",
    base64: "cha\xEEne encod\xE9e en base64",
    base64url: "cha\xEEne encod\xE9e en base64url",
    json_string: "cha\xEEne JSON",
    e164: "num\xE9ro E.164",
    jwt: "JWT",
    template_literal: "entr\xE9e"
  };
  const TypeDictionary = {
    string: "cha\xEEne",
    number: "nombre",
    int: "entier",
    boolean: "bool\xE9en",
    bigint: "grand entier",
    symbol: "symbole",
    undefined: "ind\xE9fini",
    null: "null",
    never: "jamais",
    void: "vide",
    date: "date",
    array: "tableau",
    object: "objet",
    tuple: "tuple",
    record: "enregistrement",
    map: "carte",
    set: "ensemble",
    file: "fichier",
    nonoptional: "non-optionnel",
    nan: "NaN",
    function: "fonction"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`;
        }
        return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;
        return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`;
        return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Cl\xE9 invalide dans ${issue2.origin}`;
      case "invalid_union":
        return "Entr\xE9e invalide";
      case "invalid_element":
        return `Valeur invalide dans ${issue2.origin}`;
      default:
        return `Entr\xE9e invalide`;
    }
  };
};
function fr_default() {
  return {
    localeError: error15()
  };
}

// node_modules/zod/v4/locales/fr-CA.js
var error16 = () => {
  const Sizable = {
    string: { unit: "caract\xE8res", verb: "avoir" },
    file: { unit: "octets", verb: "avoir" },
    array: { unit: "\xE9l\xE9ments", verb: "avoir" },
    set: { unit: "\xE9l\xE9ments", verb: "avoir" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "entr\xE9e",
    email: "adresse courriel",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "date-heure ISO",
    date: "date ISO",
    time: "heure ISO",
    duration: "dur\xE9e ISO",
    ipv4: "adresse IPv4",
    ipv6: "adresse IPv6",
    cidrv4: "plage IPv4",
    cidrv6: "plage IPv6",
    base64: "cha\xEEne encod\xE9e en base64",
    base64url: "cha\xEEne encod\xE9e en base64url",
    json_string: "cha\xEEne JSON",
    e164: "num\xE9ro E.164",
    jwt: "JWT",
    template_literal: "entr\xE9e"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`;
        }
        return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;
        return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "\u2264" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
        return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "\u2265" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Cl\xE9 invalide dans ${issue2.origin}`;
      case "invalid_union":
        return "Entr\xE9e invalide";
      case "invalid_element":
        return `Valeur invalide dans ${issue2.origin}`;
      default:
        return `Entr\xE9e invalide`;
    }
  };
};
function fr_CA_default() {
  return {
    localeError: error16()
  };
}

// node_modules/zod/v4/locales/he.js
var error17 = () => {
  const TypeNames = {
    string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" },
    number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" },
    boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" },
    bigint: { label: "BigInt", gender: "m" },
    date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" },
    array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" },
    object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" },
    null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" },
    undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" },
    symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" },
    function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" },
    map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" },
    set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" },
    file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" },
    promise: { label: "Promise", gender: "m" },
    NaN: { label: "NaN", gender: "m" },
    unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" },
    value: { label: "\u05E2\u05E8\u05DA", gender: "m" }
  };
  const Sizable = {
    string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" },
    file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
    array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
    set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
    number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }
    // no unit
  };
  const typeEntry = (t) => t ? TypeNames[t] : void 0;
  const typeLabel = (t) => {
    const e = typeEntry(t);
    if (e)
      return e.label;
    return t ?? TypeNames.unknown.label;
  };
  const withDefinite = (t) => `\u05D4${typeLabel(t)}`;
  const verbFor = (t) => {
    const e = typeEntry(t);
    const gender = e?.gender ?? "m";
    return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA";
  };
  const getSizing = (origin) => {
    if (!origin)
      return null;
    return Sizable[origin] ?? null;
  };
  const FormatDictionary = {
    regex: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" },
    url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" },
    emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" },
    uuid: { label: "UUID", gender: "m" },
    nanoid: { label: "nanoid", gender: "m" },
    guid: { label: "GUID", gender: "m" },
    cuid: { label: "cuid", gender: "m" },
    cuid2: { label: "cuid2", gender: "m" },
    ulid: { label: "ULID", gender: "m" },
    xid: { label: "XID", gender: "m" },
    ksuid: { label: "KSUID", gender: "m" },
    datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" },
    date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" },
    time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" },
    duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" },
    ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" },
    ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" },
    cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" },
    cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" },
    base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" },
    base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" },
    json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" },
    e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" },
    jwt: { label: "JWT", gender: "m" },
    ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    includes: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expectedKey = issue2.expected;
        const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey);
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;
        }
        return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;
      }
      case "invalid_value": {
        if (issue2.values.length === 1) {
          return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`;
        }
        const stringified = issue2.values.map((v) => stringifyPrimitive(v));
        if (issue2.values.length === 2) {
          return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`;
        }
        const lastValue = stringified[stringified.length - 1];
        const restValues = stringified.slice(0, -1).join(", ");
        return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`;
      }
      case "too_big": {
        const sizing = getSizing(issue2.origin);
        const subject = withDefinite(issue2.origin ?? "value");
        if (issue2.origin === "string") {
          return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();
        }
        if (issue2.origin === "number") {
          const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`;
          return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
        }
        if (issue2.origin === "array" || issue2.origin === "set") {
          const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
          const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit ?? ""}`;
          return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
        }
        const adj = issue2.inclusive ? "<=" : "<";
        const be = verbFor(issue2.origin ?? "value");
        if (sizing?.unit) {
          return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
        }
        return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const sizing = getSizing(issue2.origin);
        const subject = withDefinite(issue2.origin ?? "value");
        if (issue2.origin === "string") {
          return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();
        }
        if (issue2.origin === "number") {
          const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`;
          return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
        }
        if (issue2.origin === "array" || issue2.origin === "set") {
          const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
          if (issue2.minimum === 1 && issue2.inclusive) {
            const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3";
            return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`;
          }
          const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit ?? ""}`;
          return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
        }
        const adj = issue2.inclusive ? ">=" : ">";
        const be = verbFor(issue2.origin ?? "value");
        if (sizing?.unit) {
          return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`;
        const nounEntry = FormatDictionary[_issue.format];
        const noun = nounEntry?.label ?? _issue.format;
        const gender = nounEntry?.gender ?? "m";
        const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF";
        return `${noun} \u05DC\u05D0 ${adjective}`;
      }
      case "not_multiple_of":
        return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key": {
        return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`;
      }
      case "invalid_union":
        return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";
      case "invalid_element": {
        const place = withDefinite(issue2.origin ?? "array");
        return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`;
      }
      default:
        return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;
    }
  };
};
function he_default() {
  return {
    localeError: error17()
  };
}

// node_modules/zod/v4/locales/hr.js
var error18 = () => {
  const Sizable = {
    string: { unit: "znakova", verb: "imati" },
    file: { unit: "bajtova", verb: "imati" },
    array: { unit: "stavki", verb: "imati" },
    set: { unit: "stavki", verb: "imati" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "unos",
    email: "email adresa",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datum i vrijeme",
    date: "ISO datum",
    time: "ISO vrijeme",
    duration: "ISO trajanje",
    ipv4: "IPv4 adresa",
    ipv6: "IPv6 adresa",
    cidrv4: "IPv4 raspon",
    cidrv6: "IPv6 raspon",
    base64: "base64 kodirani tekst",
    base64url: "base64url kodirani tekst",
    json_string: "JSON tekst",
    e164: "E.164 broj",
    jwt: "JWT",
    template_literal: "unos"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "tekst",
    number: "broj",
    boolean: "boolean",
    array: "niz",
    object: "objekt",
    set: "skup",
    file: "datoteka",
    date: "datum",
    bigint: "bigint",
    symbol: "simbol",
    undefined: "undefined",
    null: "null",
    function: "funkcija",
    map: "mapa"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Neispravan unos: o\u010Dekuje se instanceof ${issue2.expected}, a primljeno je ${received}`;
        }
        return `Neispravan unos: o\u010Dekuje se ${expected}, a primljeno je ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Neispravna vrijednost: o\u010Dekivano ${stringifyPrimitive(issue2.values[0])}`;
        return `Neispravna opcija: o\u010Dekivano jedno od ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing)
          return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} ima ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemenata"}`;
        return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} bude ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        if (sizing) {
          return `Premalo: o\u010Dekivano da ${origin} ima ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Premalo: o\u010Dekivano da ${origin} bude ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Neispravan tekst: mora zapo\u010Dinjati s "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Neispravan tekst: mora zavr\u0161avati s "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Neispravan tekst: mora sadr\u017Eavati "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Neispravan tekst: mora odgovarati uzorku ${_issue.pattern}`;
        return `Neispravna ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Neispravan broj: mora biti vi\u0161ekratnik od ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Neprepoznat${issue2.keys.length > 1 ? "i klju\u010Devi" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Neispravan klju\u010D u ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
      case "invalid_union":
        return "Neispravan unos";
      case "invalid_element":
        return `Neispravna vrijednost u ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
      default:
        return `Neispravan unos`;
    }
  };
};
function hr_default() {
  return {
    localeError: error18()
  };
}

// node_modules/zod/v4/locales/hu.js
var error19 = () => {
  const Sizable = {
    string: { unit: "karakter", verb: "legyen" },
    file: { unit: "byte", verb: "legyen" },
    array: { unit: "elem", verb: "legyen" },
    set: { unit: "elem", verb: "legyen" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "bemenet",
    email: "email c\xEDm",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO id\u0151b\xE9lyeg",
    date: "ISO d\xE1tum",
    time: "ISO id\u0151",
    duration: "ISO id\u0151intervallum",
    ipv4: "IPv4 c\xEDm",
    ipv6: "IPv6 c\xEDm",
    cidrv4: "IPv4 tartom\xE1ny",
    cidrv6: "IPv6 tartom\xE1ny",
    base64: "base64-k\xF3dolt string",
    base64url: "base64url-k\xF3dolt string",
    json_string: "JSON string",
    e164: "E.164 sz\xE1m",
    jwt: "JWT",
    template_literal: "bemenet"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "sz\xE1m",
    array: "t\xF6mb"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`;
        }
        return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`;
        return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`;
        return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;
        if (_issue.format === "ends_with")
          return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;
        if (_issue.format === "includes")
          return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`;
        if (_issue.format === "regex")
          return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`;
        return `\xC9rv\xE9nytelen ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;
      case "unrecognized_keys":
        return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`;
      case "invalid_union":
        return "\xC9rv\xE9nytelen bemenet";
      case "invalid_element":
        return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`;
      default:
        return `\xC9rv\xE9nytelen bemenet`;
    }
  };
};
function hu_default() {
  return {
    localeError: error19()
  };
}

// node_modules/zod/v4/locales/hy.js
function getArmenianPlural(count, one2, many) {
  return Math.abs(count) === 1 ? one2 : many;
}
function withDefiniteArticle(word) {
  if (!word)
    return "";
  const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"];
  const lastChar = word[word.length - 1];
  return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568");
}
var error20 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "\u0576\u0577\u0561\u0576",
        many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    },
    file: {
      unit: {
        one: "\u0562\u0561\u0575\u0569",
        many: "\u0562\u0561\u0575\u0569\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    },
    array: {
      unit: {
        one: "\u057F\u0561\u0580\u0580",
        many: "\u057F\u0561\u0580\u0580\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    },
    set: {
      unit: {
        one: "\u057F\u0561\u0580\u0580",
        many: "\u057F\u0561\u0580\u0580\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0574\u0578\u0582\u057F\u0584",
    email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",
    url: "URL",
    emoji: "\u0567\u0574\u0578\u057B\u056B",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",
    date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",
    time: "ISO \u056A\u0561\u0574",
    duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",
    ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565",
    ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565",
    cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",
    cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",
    base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",
    base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",
    json_string: "JSON \u057F\u0578\u0572",
    e164: "E.164 \u0570\u0561\u0574\u0561\u0580",
    jwt: "JWT",
    template_literal: "\u0574\u0578\u0582\u057F\u0584"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0569\u056B\u057E",
    array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;
        }
        return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`;
        return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const maxValue = Number(issue2.maximum);
          const unit3 = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many);
          return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit3}`;
        }
        return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const minValue = Number(issue2.minimum);
          const unit3 = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many);
          return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit3}`;
        }
        return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`;
        if (_issue.format === "ends_with")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`;
        if (_issue.format === "includes")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;
        return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`;
      case "unrecognized_keys":
        return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;
      case "invalid_union":
        return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";
      case "invalid_element":
        return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;
      default:
        return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`;
    }
  };
};
function hy_default() {
  return {
    localeError: error20()
  };
}

// node_modules/zod/v4/locales/id.js
var error21 = () => {
  const Sizable = {
    string: { unit: "karakter", verb: "memiliki" },
    file: { unit: "byte", verb: "memiliki" },
    array: { unit: "item", verb: "memiliki" },
    set: { unit: "item", verb: "memiliki" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "alamat email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "tanggal dan waktu format ISO",
    date: "tanggal format ISO",
    time: "jam format ISO",
    duration: "durasi format ISO",
    ipv4: "alamat IPv4",
    ipv6: "alamat IPv6",
    cidrv4: "rentang alamat IPv4",
    cidrv6: "rentang alamat IPv6",
    base64: "string dengan enkode base64",
    base64url: "string dengan enkode base64url",
    json_string: "string JSON",
    e164: "angka E.164",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`;
        }
        return `Input tidak valid: diharapkan ${expected}, diterima ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;
        return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
        return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `String tidak valid: harus menyertakan "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `String tidak valid: harus sesuai pola ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} tidak valid`;
      }
      case "not_multiple_of":
        return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak valid di ${issue2.origin}`;
      case "invalid_union":
        return "Input tidak valid";
      case "invalid_element":
        return `Nilai tidak valid di ${issue2.origin}`;
      default:
        return `Input tidak valid`;
    }
  };
};
function id_default() {
  return {
    localeError: error21()
  };
}

// node_modules/zod/v4/locales/is.js
var error22 = () => {
  const Sizable = {
    string: { unit: "stafi", verb: "a\xF0 hafa" },
    file: { unit: "b\xE6ti", verb: "a\xF0 hafa" },
    array: { unit: "hluti", verb: "a\xF0 hafa" },
    set: { unit: "hluti", verb: "a\xF0 hafa" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "gildi",
    email: "netfang",
    url: "vefsl\xF3\xF0",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO dagsetning og t\xEDmi",
    date: "ISO dagsetning",
    time: "ISO t\xEDmi",
    duration: "ISO t\xEDmalengd",
    ipv4: "IPv4 address",
    ipv6: "IPv6 address",
    cidrv4: "IPv4 range",
    cidrv6: "IPv6 range",
    base64: "base64-encoded strengur",
    base64url: "base64url-encoded strengur",
    json_string: "JSON strengur",
    e164: "E.164 t\xF6lugildi",
    jwt: "JWT",
    template_literal: "gildi"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "n\xFAmer",
    array: "fylki"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`;
        }
        return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`;
        return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`;
        return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`;
        return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Rangur lykill \xED ${issue2.origin}`;
      case "invalid_union":
        return "Rangt gildi";
      case "invalid_element":
        return `Rangt gildi \xED ${issue2.origin}`;
      default:
        return `Rangt gildi`;
    }
  };
};
function is_default() {
  return {
    localeError: error22()
  };
}

// node_modules/zod/v4/locales/it.js
var error23 = () => {
  const Sizable = {
    string: { unit: "caratteri", verb: "avere" },
    file: { unit: "byte", verb: "avere" },
    array: { unit: "elementi", verb: "avere" },
    set: { unit: "elementi", verb: "avere" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "indirizzo email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "data e ora ISO",
    date: "data ISO",
    time: "ora ISO",
    duration: "durata ISO",
    ipv4: "indirizzo IPv4",
    ipv6: "indirizzo IPv6",
    cidrv4: "intervallo IPv4",
    cidrv6: "intervallo IPv6",
    base64: "stringa codificata in base64",
    base64url: "URL codificata in base64",
    json_string: "stringa JSON",
    e164: "numero E.164",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "numero",
    array: "vettore"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`;
        }
        return `Input non valido: atteso ${expected}, ricevuto ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;
        return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`;
        return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Stringa non valida: deve includere "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
        return `Input non valido: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Chiave non valida in ${issue2.origin}`;
      case "invalid_union":
        return "Input non valido";
      case "invalid_element":
        return `Valore non valido in ${issue2.origin}`;
      default:
        return `Input non valido`;
    }
  };
};
function it_default() {
  return {
    localeError: error23()
  };
}

// node_modules/zod/v4/locales/ja.js
var error24 = () => {
  const Sizable = {
    string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" },
    file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" },
    array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" },
    set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u5165\u529B\u5024",
    email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",
    url: "URL",
    emoji: "\u7D75\u6587\u5B57",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO\u65E5\u6642",
    date: "ISO\u65E5\u4ED8",
    time: "ISO\u6642\u523B",
    duration: "ISO\u671F\u9593",
    ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9",
    ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9",
    cidrv4: "IPv4\u7BC4\u56F2",
    cidrv6: "IPv6\u7BC4\u56F2",
    base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
    base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
    json_string: "JSON\u6587\u5B57\u5217",
    e164: "E.164\u756A\u53F7",
    jwt: "JWT",
    template_literal: "\u5165\u529B\u5024"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u6570\u5024",
    array: "\u914D\u5217"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;
        }
        return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;
        return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      case "too_big": {
        const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        if (_issue.format === "ends_with")
          return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        if (_issue.format === "includes")
          return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        if (_issue.format === "regex")
          return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      case "unrecognized_keys":
        return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`;
      case "invalid_key":
        return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;
      case "invalid_union":
        return "\u7121\u52B9\u306A\u5165\u529B";
      case "invalid_element":
        return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;
      default:
        return `\u7121\u52B9\u306A\u5165\u529B`;
    }
  };
};
function ja_default() {
  return {
    localeError: error24()
  };
}

// node_modules/zod/v4/locales/ka.js
var error25 = () => {
  const Sizable = {
    string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" },
    file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" },
    array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" },
    set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",
    email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
    url: "URL",
    emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",
    date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",
    time: "\u10D3\u10E0\u10DD",
    duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",
    ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
    ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
    cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",
    cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",
    base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",
    base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",
    json_string: "JSON \u10D5\u10D4\u10DA\u10D8",
    e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",
    jwt: "JWT",
    template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",
    string: "\u10D5\u10D4\u10DA\u10D8",
    boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",
    function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",
    array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;
        }
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`;
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
        return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`;
        }
        if (_issue.format === "ends_with")
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`;
        if (_issue.format === "includes")
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`;
        if (_issue.format === "regex")
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`;
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;
      case "unrecognized_keys":
        return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`;
      case "invalid_union":
        return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";
      case "invalid_element":
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`;
      default:
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`;
    }
  };
};
function ka_default() {
  return {
    localeError: error25()
  };
}

// node_modules/zod/v4/locales/km.js
var error26 = () => {
  const Sizable = {
    string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
    file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
    array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
    set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",
    email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",
    url: "URL",
    emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",
    date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",
    time: "\u1798\u17C9\u17C4\u1784 ISO",
    duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",
    ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
    ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
    cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
    cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
    base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",
    base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",
    json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",
    e164: "\u179B\u17C1\u1781 E.164",
    jwt: "JWT",
    template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u179B\u17C1\u1781",
    array: "\u17A2\u17B6\u179A\u17C1 (Array)",
    null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`;
        }
        return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`;
        return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`;
        return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`;
        return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
      case "invalid_union":
        return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
      case "invalid_element":
        return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
      default:
        return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
    }
  };
};
function km_default() {
  return {
    localeError: error26()
  };
}

// node_modules/zod/v4/locales/kh.js
function kh_default() {
  return km_default();
}

// node_modules/zod/v4/locales/ko.js
var error27 = () => {
  const Sizable = {
    string: { unit: "\uBB38\uC790", verb: "to have" },
    file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" },
    array: { unit: "\uAC1C", verb: "to have" },
    set: { unit: "\uAC1C", verb: "to have" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\uC785\uB825",
    email: "\uC774\uBA54\uC77C \uC8FC\uC18C",
    url: "URL",
    emoji: "\uC774\uBAA8\uC9C0",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04",
    date: "ISO \uB0A0\uC9DC",
    time: "ISO \uC2DC\uAC04",
    duration: "ISO \uAE30\uAC04",
    ipv4: "IPv4 \uC8FC\uC18C",
    ipv6: "IPv6 \uC8FC\uC18C",
    cidrv4: "IPv4 \uBC94\uC704",
    cidrv6: "IPv6 \uBC94\uC704",
    base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
    base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
    json_string: "JSON \uBB38\uC790\uC5F4",
    e164: "E.164 \uBC88\uD638",
    jwt: "JWT",
    template_literal: "\uC785\uB825"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`;
        }
        return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;
        return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
      case "too_big": {
        const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC";
        const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
        const sizing = getSizing(issue2.origin);
        const unit3 = sizing?.unit ?? "\uC694\uC18C";
        if (sizing)
          return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit3} ${adj}${suffix}`;
        return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC";
        const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
        const sizing = getSizing(issue2.origin);
        const unit3 = sizing?.unit ?? "\uC694\uC18C";
        if (sizing) {
          return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit3} ${adj}${suffix}`;
        }
        return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;
        }
        if (_issue.format === "ends_with")
          return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;
        if (_issue.format === "includes")
          return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;
        if (_issue.format === "regex")
          return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;
        return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
      case "unrecognized_keys":
        return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`;
      case "invalid_union":
        return `\uC798\uBABB\uB41C \uC785\uB825`;
      case "invalid_element":
        return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`;
      default:
        return `\uC798\uBABB\uB41C \uC785\uB825`;
    }
  };
};
function ko_default() {
  return {
    localeError: error27()
  };
}

// node_modules/zod/v4/locales/lt.js
var capitalizeFirstCharacter = (text) => {
  return text.charAt(0).toUpperCase() + text.slice(1);
};
function getUnitTypeFromNumber(number8) {
  const abs = Math.abs(number8);
  const last = abs % 10;
  const last2 = abs % 100;
  if (last2 >= 11 && last2 <= 19 || last === 0)
    return "many";
  if (last === 1)
    return "one";
  return "few";
}
var error28 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "simbolis",
        few: "simboliai",
        many: "simboli\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip",
          notInclusive: "turi b\u016Bti trumpesn\u0117 kaip"
        },
        bigger: {
          inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip",
          notInclusive: "turi b\u016Bti ilgesn\u0117 kaip"
        }
      }
    },
    file: {
      unit: {
        one: "baitas",
        few: "baitai",
        many: "bait\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi b\u016Bti ne didesnis kaip",
          notInclusive: "turi b\u016Bti ma\u017Eesnis kaip"
        },
        bigger: {
          inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip",
          notInclusive: "turi b\u016Bti didesnis kaip"
        }
      }
    },
    array: {
      unit: {
        one: "element\u0105",
        few: "elementus",
        many: "element\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi tur\u0117ti ne daugiau kaip",
          notInclusive: "turi tur\u0117ti ma\u017Eiau kaip"
        },
        bigger: {
          inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip",
          notInclusive: "turi tur\u0117ti daugiau kaip"
        }
      }
    },
    set: {
      unit: {
        one: "element\u0105",
        few: "elementus",
        many: "element\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi tur\u0117ti ne daugiau kaip",
          notInclusive: "turi tur\u0117ti ma\u017Eiau kaip"
        },
        bigger: {
          inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip",
          notInclusive: "turi tur\u0117ti daugiau kaip"
        }
      }
    }
  };
  function getSizing(origin, unitType, inclusive, targetShouldBe) {
    const result = Sizable[origin] ?? null;
    if (result === null)
      return result;
    return {
      unit: result.unit[unitType],
      verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"]
    };
  }
  const FormatDictionary = {
    regex: "\u012Fvestis",
    email: "el. pa\u0161to adresas",
    url: "URL",
    emoji: "jaustukas",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO data ir laikas",
    date: "ISO data",
    time: "ISO laikas",
    duration: "ISO trukm\u0117",
    ipv4: "IPv4 adresas",
    ipv6: "IPv6 adresas",
    cidrv4: "IPv4 tinklo prefiksas (CIDR)",
    cidrv6: "IPv6 tinklo prefiksas (CIDR)",
    base64: "base64 u\u017Ekoduota eilut\u0117",
    base64url: "base64url u\u017Ekoduota eilut\u0117",
    json_string: "JSON eilut\u0117",
    e164: "E.164 numeris",
    jwt: "JWT",
    template_literal: "\u012Fvestis"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "skai\u010Dius",
    bigint: "sveikasis skai\u010Dius",
    string: "eilut\u0117",
    boolean: "login\u0117 reik\u0161m\u0117",
    undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117",
    function: "funkcija",
    symbol: "simbolis",
    array: "masyvas",
    object: "objektas",
    null: "nulin\u0117 reik\u0161m\u0117"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`;
        }
        return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`;
        return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`;
      case "too_big": {
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller");
        if (sizing?.verb)
          return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "element\u0173"}`;
        const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip";
        return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`;
      }
      case "too_small": {
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger");
        if (sizing?.verb)
          return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "element\u0173"}`;
        const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip";
        return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Eilut\u0117 privalo atitikti ${_issue.pattern}`;
        return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`;
      case "unrecognized_keys":
        return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return "Rastas klaidingas raktas";
      case "invalid_union":
        return "Klaidinga \u012Fvestis";
      case "invalid_element": {
        const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
        return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`;
      }
      default:
        return "Klaidinga \u012Fvestis";
    }
  };
};
function lt_default() {
  return {
    localeError: error28()
  };
}

// node_modules/zod/v4/locales/mk.js
var error29 = () => {
  const Sizable = {
    string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
    file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
    array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
    set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0432\u043D\u0435\u0441",
    email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",
    url: "URL",
    emoji: "\u0435\u043C\u043E\u045F\u0438",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",
    date: "ISO \u0434\u0430\u0442\u0443\u043C",
    time: "ISO \u0432\u0440\u0435\u043C\u0435",
    duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",
    ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",
    ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",
    cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433",
    cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433",
    base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
    base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
    json_string: "JSON \u043D\u0438\u0437\u0430",
    e164: "E.164 \u0431\u0440\u043E\u0458",
    jwt: "JWT",
    template_literal: "\u0432\u043D\u0435\u0441"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0431\u0440\u043E\u0458",
    array: "\u043D\u0438\u0437\u0430"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;
        }
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
        return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;
        return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`;
        return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`;
      case "invalid_union":
        return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";
      case "invalid_element":
        return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`;
      default:
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`;
    }
  };
};
function mk_default() {
  return {
    localeError: error29()
  };
}

// node_modules/zod/v4/locales/ms.js
var error30 = () => {
  const Sizable = {
    string: { unit: "aksara", verb: "mempunyai" },
    file: { unit: "bait", verb: "mempunyai" },
    array: { unit: "elemen", verb: "mempunyai" },
    set: { unit: "elemen", verb: "mempunyai" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "alamat e-mel",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "tarikh masa ISO",
    date: "tarikh ISO",
    time: "masa ISO",
    duration: "tempoh ISO",
    ipv4: "alamat IPv4",
    ipv6: "alamat IPv6",
    cidrv4: "julat IPv4",
    cidrv6: "julat IPv6",
    base64: "string dikodkan base64",
    base64url: "string dikodkan base64url",
    json_string: "string JSON",
    e164: "nombor E.164",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "nombor"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`;
        }
        return `Input tidak sah: dijangka ${expected}, diterima ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;
        return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
        return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `String tidak sah: mesti mengandungi "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} tidak sah`;
      }
      case "not_multiple_of":
        return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak sah dalam ${issue2.origin}`;
      case "invalid_union":
        return "Input tidak sah";
      case "invalid_element":
        return `Nilai tidak sah dalam ${issue2.origin}`;
      default:
        return `Input tidak sah`;
    }
  };
};
function ms_default() {
  return {
    localeError: error30()
  };
}

// node_modules/zod/v4/locales/nl.js
var error31 = () => {
  const Sizable = {
    string: { unit: "tekens", verb: "heeft" },
    file: { unit: "bytes", verb: "heeft" },
    array: { unit: "elementen", verb: "heeft" },
    set: { unit: "elementen", verb: "heeft" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "invoer",
    email: "emailadres",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datum en tijd",
    date: "ISO datum",
    time: "ISO tijd",
    duration: "ISO duur",
    ipv4: "IPv4-adres",
    ipv6: "IPv6-adres",
    cidrv4: "IPv4-bereik",
    cidrv6: "IPv6-bereik",
    base64: "base64-gecodeerde tekst",
    base64url: "base64 URL-gecodeerde tekst",
    json_string: "JSON string",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "invoer"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "getal"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`;
        }
        return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;
        return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot";
        if (sizing)
          return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`;
        return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein";
        if (sizing) {
          return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;
        }
        if (_issue.format === "ends_with")
          return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;
        if (_issue.format === "includes")
          return `Ongeldige tekst: moet "${_issue.includes}" bevatten`;
        if (_issue.format === "regex")
          return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;
        return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;
      case "unrecognized_keys":
        return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ongeldige key in ${issue2.origin}`;
      case "invalid_union":
        return "Ongeldige invoer";
      case "invalid_element":
        return `Ongeldige waarde in ${issue2.origin}`;
      default:
        return `Ongeldige invoer`;
    }
  };
};
function nl_default() {
  return {
    localeError: error31()
  };
}

// node_modules/zod/v4/locales/no.js
var error32 = () => {
  const Sizable = {
    string: { unit: "tegn", verb: "\xE5 ha" },
    file: { unit: "bytes", verb: "\xE5 ha" },
    array: { unit: "elementer", verb: "\xE5 inneholde" },
    set: { unit: "elementer", verb: "\xE5 inneholde" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "e-postadresse",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO dato- og klokkeslett",
    date: "ISO-dato",
    time: "ISO-klokkeslett",
    duration: "ISO-varighet",
    ipv4: "IPv4-omr\xE5de",
    ipv6: "IPv6-omr\xE5de",
    cidrv4: "IPv4-spekter",
    cidrv6: "IPv6-spekter",
    base64: "base64-enkodet streng",
    base64url: "base64url-enkodet streng",
    json_string: "JSON-streng",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "tall",
    array: "liste"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`;
        }
        return `Ugyldig input: forventet ${expected}, fikk ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;
        return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`;
        return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`;
        return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig n\xF8kkel i ${issue2.origin}`;
      case "invalid_union":
        return "Ugyldig input";
      case "invalid_element":
        return `Ugyldig verdi i ${issue2.origin}`;
      default:
        return `Ugyldig input`;
    }
  };
};
function no_default() {
  return {
    localeError: error32()
  };
}

// node_modules/zod/v4/locales/ota.js
var error33 = () => {
  const Sizable = {
    string: { unit: "harf", verb: "olmal\u0131d\u0131r" },
    file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
    array: { unit: "unsur", verb: "olmal\u0131d\u0131r" },
    set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "giren",
    email: "epostag\xE2h",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO heng\xE2m\u0131",
    date: "ISO tarihi",
    time: "ISO zaman\u0131",
    duration: "ISO m\xFCddeti",
    ipv4: "IPv4 ni\u015F\xE2n\u0131",
    ipv6: "IPv6 ni\u015F\xE2n\u0131",
    cidrv4: "IPv4 menzili",
    cidrv6: "IPv6 menzili",
    base64: "base64-\u015Fifreli metin",
    base64url: "base64url-\u015Fifreli metin",
    json_string: "JSON metin",
    e164: "E.164 say\u0131s\u0131",
    jwt: "JWT",
    template_literal: "giren"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "numara",
    array: "saf",
    null: "gayb"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`;
        }
        return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;
        return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`;
        return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`;
        }
        return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`;
        if (_issue.format === "ends_with")
          return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`;
        if (_issue.format === "includes")
          return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`;
        if (_issue.format === "regex")
          return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`;
        return `F\xE2sit ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`;
      case "invalid_union":
        return "Giren tan\u0131namad\u0131.";
      case "invalid_element":
        return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;
      default:
        return `K\u0131ymet tan\u0131namad\u0131.`;
    }
  };
};
function ota_default() {
  return {
    localeError: error33()
  };
}

// node_modules/zod/v4/locales/ps.js
var error34 = () => {
  const Sizable = {
    string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" },
    file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" },
    array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" },
    set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0648\u0631\u0648\u062F\u064A",
    email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",
    url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644",
    emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",
    date: "\u0646\u06D0\u067C\u0647",
    time: "\u0648\u062E\u062A",
    duration: "\u0645\u0648\u062F\u0647",
    ipv4: "\u062F IPv4 \u067E\u062A\u0647",
    ipv6: "\u062F IPv6 \u067E\u062A\u0647",
    cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647",
    cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647",
    base64: "base64-encoded \u0645\u062A\u0646",
    base64url: "base64url-encoded \u0645\u062A\u0646",
    json_string: "JSON \u0645\u062A\u0646",
    e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",
    jwt: "JWT",
    template_literal: "\u0648\u0631\u0648\u062F\u064A"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0639\u062F\u062F",
    array: "\u0627\u0631\u06D0"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;
        }
        return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;
      }
      case "invalid_value":
        if (issue2.values.length === 1) {
          return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`;
        }
        return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;
        }
        return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`;
        }
        return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;
        }
        if (_issue.format === "ends_with") {
          return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;
        }
        if (_issue.format === "includes") {
          return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`;
        }
        if (_issue.format === "regex") {
          return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;
        }
        return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`;
      }
      case "not_multiple_of":
        return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;
      case "unrecognized_keys":
        return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
      case "invalid_union":
        return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
      case "invalid_element":
        return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
      default:
        return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
    }
  };
};
function ps_default() {
  return {
    localeError: error34()
  };
}

// node_modules/zod/v4/locales/pl.js
var error35 = () => {
  const Sizable = {
    string: { unit: "znak\xF3w", verb: "mie\u0107" },
    file: { unit: "bajt\xF3w", verb: "mie\u0107" },
    array: { unit: "element\xF3w", verb: "mie\u0107" },
    set: { unit: "element\xF3w", verb: "mie\u0107" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "wyra\u017Cenie",
    email: "adres email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "data i godzina w formacie ISO",
    date: "data w formacie ISO",
    time: "godzina w formacie ISO",
    duration: "czas trwania ISO",
    ipv4: "adres IPv4",
    ipv6: "adres IPv6",
    cidrv4: "zakres IPv4",
    cidrv6: "zakres IPv6",
    base64: "ci\u0105g znak\xF3w zakodowany w formacie base64",
    base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url",
    json_string: "ci\u0105g znak\xF3w w formacie JSON",
    e164: "liczba E.164",
    jwt: "JWT",
    template_literal: "wej\u015Bcie"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "liczba",
    array: "tablica"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`;
        }
        return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;
        return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`;
        }
        return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`;
        }
        return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`;
        return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Nieprawid\u0142owy klucz w ${issue2.origin}`;
      case "invalid_union":
        return "Nieprawid\u0142owe dane wej\u015Bciowe";
      case "invalid_element":
        return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`;
      default:
        return `Nieprawid\u0142owe dane wej\u015Bciowe`;
    }
  };
};
function pl_default() {
  return {
    localeError: error35()
  };
}

// node_modules/zod/v4/locales/pt.js
var error36 = () => {
  const Sizable = {
    string: { unit: "caracteres", verb: "ter" },
    file: { unit: "bytes", verb: "ter" },
    array: { unit: "itens", verb: "ter" },
    set: { unit: "itens", verb: "ter" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "padr\xE3o",
    email: "endere\xE7o de e-mail",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "data e hora ISO",
    date: "data ISO",
    time: "hora ISO",
    duration: "dura\xE7\xE3o ISO",
    ipv4: "endere\xE7o IPv4",
    ipv6: "endere\xE7o IPv6",
    cidrv4: "faixa de IPv4",
    cidrv6: "faixa de IPv6",
    base64: "texto codificado em base64",
    base64url: "URL codificada em base64",
    json_string: "texto JSON",
    e164: "n\xFAmero E.164",
    jwt: "JWT",
    template_literal: "entrada"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "n\xFAmero",
    null: "nulo"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`;
        }
        return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`;
        return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
        return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Chave inv\xE1lida em ${issue2.origin}`;
      case "invalid_union":
        return "Entrada inv\xE1lida";
      case "invalid_element":
        return `Valor inv\xE1lido em ${issue2.origin}`;
      default:
        return `Campo inv\xE1lido`;
    }
  };
};
function pt_default() {
  return {
    localeError: error36()
  };
}

// node_modules/zod/v4/locales/ro.js
var error37 = () => {
  const Sizable = {
    string: { unit: "caractere", verb: "s\u0103 aib\u0103" },
    file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" },
    array: { unit: "elemente", verb: "s\u0103 aib\u0103" },
    set: { unit: "elemente", verb: "s\u0103 aib\u0103" },
    map: { unit: "intr\u0103ri", verb: "s\u0103 aib\u0103" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "intrare",
    email: "adres\u0103 de email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "dat\u0103 \u0219i or\u0103 ISO",
    date: "dat\u0103 ISO",
    time: "or\u0103 ISO",
    duration: "durat\u0103 ISO",
    ipv4: "adres\u0103 IPv4",
    ipv6: "adres\u0103 IPv6",
    mac: "adres\u0103 MAC",
    cidrv4: "interval IPv4",
    cidrv6: "interval IPv6",
    base64: "\u0219ir codat base64",
    base64url: "\u0219ir codat base64url",
    json_string: "\u0219ir JSON",
    e164: "num\u0103r E.164",
    jwt: "JWT",
    template_literal: "intrare"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "\u0219ir",
    number: "num\u0103r",
    boolean: "boolean",
    function: "func\u021Bie",
    array: "matrice",
    object: "obiect",
    undefined: "nedefinit",
    symbol: "simbol",
    bigint: "num\u0103r mare",
    void: "void",
    never: "never",
    map: "hart\u0103",
    set: "set"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        return `Intrare invalid\u0103: a\u0219teptat ${expected}, primit ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Intrare invalid\u0103: a\u0219teptat ${stringifyPrimitive(issue2.values[0])}`;
        return `Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemente"}`;
        return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} s\u0103 fie ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Prea mic: a\u0219teptat ca ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Prea mic: a\u0219teptat ca ${issue2.origin} s\u0103 fie ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u0218ir invalid: trebuie s\u0103 se termine cu "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u0218ir invalid: trebuie s\u0103 includ\u0103 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${_issue.pattern}`;
        return `Format invalid: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Chei nerecunoscute: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Cheie invalid\u0103 \xEEn ${issue2.origin}`;
      case "invalid_union":
        return "Intrare invalid\u0103";
      case "invalid_element":
        return `Valoare invalid\u0103 \xEEn ${issue2.origin}`;
      default:
        return `Intrare invalid\u0103`;
    }
  };
};
function ro_default() {
  return {
    localeError: error37()
  };
}

// node_modules/zod/v4/locales/ru.js
function getRussianPlural(count, one2, few, many) {
  const absCount = Math.abs(count);
  const lastDigit = absCount % 10;
  const lastTwoDigits = absCount % 100;
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
    return many;
  }
  if (lastDigit === 1) {
    return one2;
  }
  if (lastDigit >= 2 && lastDigit <= 4) {
    return few;
  }
  return many;
}
var error38 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "\u0441\u0438\u043C\u0432\u043E\u043B",
        few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430",
        many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"
      },
      verb: "\u0438\u043C\u0435\u0442\u044C"
    },
    file: {
      unit: {
        one: "\u0431\u0430\u0439\u0442",
        few: "\u0431\u0430\u0439\u0442\u0430",
        many: "\u0431\u0430\u0439\u0442"
      },
      verb: "\u0438\u043C\u0435\u0442\u044C"
    },
    array: {
      unit: {
        one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
        few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
        many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
      },
      verb: "\u0438\u043C\u0435\u0442\u044C"
    },
    set: {
      unit: {
        one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
        few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
        many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
      },
      verb: "\u0438\u043C\u0435\u0442\u044C"
    }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0432\u0432\u043E\u0434",
    email: "email \u0430\u0434\u0440\u0435\u0441",
    url: "URL",
    emoji: "\u044D\u043C\u043E\u0434\u0437\u0438",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",
    date: "ISO \u0434\u0430\u0442\u0430",
    time: "ISO \u0432\u0440\u0435\u043C\u044F",
    duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",
    ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441",
    ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441",
    cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
    cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
    base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",
    base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",
    json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430",
    e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
    jwt: "JWT",
    template_literal: "\u0432\u0432\u043E\u0434"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0447\u0438\u0441\u043B\u043E",
    array: "\u043C\u0430\u0441\u0441\u0438\u0432"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`;
        }
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`;
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const maxValue = Number(issue2.maximum);
          const unit3 = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit3}`;
        }
        return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const minValue = Number(issue2.minimum);
          const unit3 = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit3}`;
        }
        return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;
      case "invalid_union":
        return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";
      case "invalid_element":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`;
      default:
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`;
    }
  };
};
function ru_default() {
  return {
    localeError: error38()
  };
}

// node_modules/zod/v4/locales/sl.js
var error39 = () => {
  const Sizable = {
    string: { unit: "znakov", verb: "imeti" },
    file: { unit: "bajtov", verb: "imeti" },
    array: { unit: "elementov", verb: "imeti" },
    set: { unit: "elementov", verb: "imeti" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "vnos",
    email: "e-po\u0161tni naslov",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO datum in \u010Das",
    date: "ISO datum",
    time: "ISO \u010Das",
    duration: "ISO trajanje",
    ipv4: "IPv4 naslov",
    ipv6: "IPv6 naslov",
    cidrv4: "obseg IPv4",
    cidrv6: "obseg IPv6",
    base64: "base64 kodiran niz",
    base64url: "base64url kodiran niz",
    json_string: "JSON niz",
    e164: "E.164 \u0161tevilka",
    jwt: "JWT",
    template_literal: "vnos"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0161tevilo",
    array: "tabela"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`;
        }
        return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`;
        return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`;
        return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Neveljaven niz: mora vsebovati "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;
        return `Neveljaven ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Neveljaven klju\u010D v ${issue2.origin}`;
      case "invalid_union":
        return "Neveljaven vnos";
      case "invalid_element":
        return `Neveljavna vrednost v ${issue2.origin}`;
      default:
        return "Neveljaven vnos";
    }
  };
};
function sl_default() {
  return {
    localeError: error39()
  };
}

// node_modules/zod/v4/locales/sv.js
var error40 = () => {
  const Sizable = {
    string: { unit: "tecken", verb: "att ha" },
    file: { unit: "bytes", verb: "att ha" },
    array: { unit: "objekt", verb: "att inneh\xE5lla" },
    set: { unit: "objekt", verb: "att inneh\xE5lla" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "regulj\xE4rt uttryck",
    email: "e-postadress",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO-datum och tid",
    date: "ISO-datum",
    time: "ISO-tid",
    duration: "ISO-varaktighet",
    ipv4: "IPv4-intervall",
    ipv6: "IPv6-intervall",
    cidrv4: "IPv4-spektrum",
    cidrv6: "IPv6-spektrum",
    base64: "base64-kodad str\xE4ng",
    base64url: "base64url-kodad str\xE4ng",
    json_string: "JSON-str\xE4ng",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "mall-literal"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "antal",
    array: "lista"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`;
        }
        return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`;
        return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
        }
        return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`;
        return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`;
      case "invalid_union":
        return "Ogiltig input";
      case "invalid_element":
        return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`;
      default:
        return `Ogiltig input`;
    }
  };
};
function sv_default() {
  return {
    localeError: error40()
  };
}

// node_modules/zod/v4/locales/ta.js
var error41 = () => {
  const Sizable = {
    string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
    file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
    array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
    set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",
    email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
    date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF",
    time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
    duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",
    ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
    ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
    cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
    cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
    base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
    base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
    json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD",
    e164: "E.164 \u0B8E\u0BA3\u0BCD",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0B8E\u0BA3\u0BCD",
    array: "\u0B85\u0BA3\u0BBF",
    null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;
        }
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`;
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        }
        return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        }
        return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (_issue.format === "ends_with")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (_issue.format === "includes")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (_issue.format === "regex")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      case "unrecognized_keys":
        return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;
      case "invalid_union":
        return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";
      case "invalid_element":
        return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;
      default:
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`;
    }
  };
};
function ta_default() {
  return {
    localeError: error41()
  };
}

// node_modules/zod/v4/locales/th.js
var error42 = () => {
  const Sizable = {
    string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
    file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
    array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
    set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",
    email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",
    url: "URL",
    emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
    date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",
    time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
    duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
    ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",
    ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",
    cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",
    cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",
    base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",
    base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",
    json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",
    e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",
    jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",
    template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",
    array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",
    null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`;
        }
        return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`;
        return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;
        return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;
        if (_issue.format === "regex")
          return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`;
        return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;
      case "unrecognized_keys":
        return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
      case "invalid_union":
        return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";
      case "invalid_element":
        return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
      default:
        return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`;
    }
  };
};
function th_default() {
  return {
    localeError: error42()
  };
}

// node_modules/zod/v4/locales/tr.js
var error43 = () => {
  const Sizable = {
    string: { unit: "karakter", verb: "olmal\u0131" },
    file: { unit: "bayt", verb: "olmal\u0131" },
    array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" },
    set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "girdi",
    email: "e-posta adresi",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO tarih ve saat",
    date: "ISO tarih",
    time: "ISO saat",
    duration: "ISO s\xFCre",
    ipv4: "IPv4 adresi",
    ipv6: "IPv6 adresi",
    cidrv4: "IPv4 aral\u0131\u011F\u0131",
    cidrv6: "IPv6 aral\u0131\u011F\u0131",
    base64: "base64 ile \u015Fifrelenmi\u015F metin",
    base64url: "base64url ile \u015Fifrelenmi\u015F metin",
    json_string: "JSON dizesi",
    e164: "E.164 say\u0131s\u0131",
    jwt: "JWT",
    template_literal: "\u015Eablon dizesi"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`;
        }
        return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`;
        return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`;
        return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`;
        if (_issue.format === "ends_with")
          return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`;
        if (_issue.format === "includes")
          return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`;
        if (_issue.format === "regex")
          return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`;
        return `Ge\xE7ersiz ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`;
      case "invalid_union":
        return "Ge\xE7ersiz de\u011Fer";
      case "invalid_element":
        return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;
      default:
        return `Ge\xE7ersiz de\u011Fer`;
    }
  };
};
function tr_default() {
  return {
    localeError: error43()
  };
}

// node_modules/zod/v4/locales/uk.js
var error44 = () => {
  const Sizable = {
    string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
    file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
    array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
    set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",
    email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",
    url: "URL",
    emoji: "\u0435\u043C\u043E\u0434\u0437\u0456",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",
    date: "\u0434\u0430\u0442\u0430 ISO",
    time: "\u0447\u0430\u0441 ISO",
    duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",
    ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",
    ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",
    cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",
    cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",
    base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",
    base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",
    json_string: "\u0440\u044F\u0434\u043E\u043A JSON",
    e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
    jwt: "JWT",
    template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0447\u0438\u0441\u043B\u043E",
    array: "\u043C\u0430\u0441\u0438\u0432"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;
        }
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
      case "invalid_union":
        return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";
      case "invalid_element":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`;
      default:
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`;
    }
  };
};
function uk_default() {
  return {
    localeError: error44()
  };
}

// node_modules/zod/v4/locales/ua.js
function ua_default() {
  return uk_default();
}

// node_modules/zod/v4/locales/ur.js
var error45 = () => {
  const Sizable = {
    string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" },
    file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" },
    array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" },
    set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0627\u0646 \u067E\u0679",
    email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",
    url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",
    emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
    uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",
    uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",
    nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",
    ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",
    xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",
    ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",
    date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",
    time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",
    duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",
    ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",
    ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",
    cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",
    cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",
    base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
    base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
    json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",
    e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631",
    jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",
    template_literal: "\u0627\u0646 \u067E\u0679"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0646\u0645\u0628\u0631",
    array: "\u0622\u0631\u06D2",
    null: "\u0646\u0644"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
        }
        return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
        return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
        return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
        }
        return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        }
        if (_issue.format === "ends_with")
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        if (_issue.format === "includes")
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        if (_issue.format === "regex")
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
      case "unrecognized_keys":
        return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
      case "invalid_key":
        return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;
      case "invalid_union":
        return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";
      case "invalid_element":
        return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;
      default:
        return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`;
    }
  };
};
function ur_default() {
  return {
    localeError: error45()
  };
}

// node_modules/zod/v4/locales/uz.js
var error46 = () => {
  const Sizable = {
    string: { unit: "belgi", verb: "bo\u2018lishi kerak" },
    file: { unit: "bayt", verb: "bo\u2018lishi kerak" },
    array: { unit: "element", verb: "bo\u2018lishi kerak" },
    set: { unit: "element", verb: "bo\u2018lishi kerak" },
    map: { unit: "yozuv", verb: "bo\u2018lishi kerak" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "kirish",
    email: "elektron pochta manzili",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO sana va vaqti",
    date: "ISO sana",
    time: "ISO vaqt",
    duration: "ISO davomiylik",
    ipv4: "IPv4 manzil",
    ipv6: "IPv6 manzil",
    mac: "MAC manzil",
    cidrv4: "IPv4 diapazon",
    cidrv6: "IPv6 diapazon",
    base64: "base64 kodlangan satr",
    base64url: "base64url kodlangan satr",
    json_string: "JSON satr",
    e164: "E.164 raqam",
    jwt: "JWT",
    template_literal: "kirish"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "raqam",
    array: "massiv"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`;
        }
        return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`;
        return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`;
        return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`;
        if (_issue.format === "ends_with")
          return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`;
        if (_issue.format === "includes")
          return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`;
        if (_issue.format === "regex")
          return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;
        return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`;
      case "unrecognized_keys":
        return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`;
      case "invalid_union":
        return "Noto\u2018g\u2018ri kirish";
      case "invalid_element":
        return `${issue2.origin} da noto\u2018g\u2018ri qiymat`;
      default:
        return `Noto\u2018g\u2018ri kirish`;
    }
  };
};
function uz_default() {
  return {
    localeError: error46()
  };
}

// node_modules/zod/v4/locales/vi.js
var error47 = () => {
  const Sizable = {
    string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" },
    file: { unit: "byte", verb: "c\xF3" },
    array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" },
    set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u0111\u1EA7u v\xE0o",
    email: "\u0111\u1ECBa ch\u1EC9 email",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ng\xE0y gi\u1EDD ISO",
    date: "ng\xE0y ISO",
    time: "gi\u1EDD ISO",
    duration: "kho\u1EA3ng th\u1EDDi gian ISO",
    ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4",
    ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6",
    cidrv4: "d\u1EA3i IPv4",
    cidrv6: "d\u1EA3i IPv6",
    base64: "chu\u1ED7i m\xE3 h\xF3a base64",
    base64url: "chu\u1ED7i m\xE3 h\xF3a base64url",
    json_string: "chu\u1ED7i JSON",
    e164: "s\u1ED1 E.164",
    jwt: "JWT",
    template_literal: "\u0111\u1EA7u v\xE0o"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "s\u1ED1",
    array: "m\u1EA3ng"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`;
        }
        return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`;
        return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`;
        return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`;
        return `${FormatDictionary[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`;
      }
      case "not_multiple_of":
        return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
      case "invalid_union":
        return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";
      case "invalid_element":
        return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
      default:
        return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`;
    }
  };
};
function vi_default() {
  return {
    localeError: error47()
  };
}

// node_modules/zod/v4/locales/zh-CN.js
var error48 = () => {
  const Sizable = {
    string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" },
    file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" },
    array: { unit: "\u9879", verb: "\u5305\u542B" },
    set: { unit: "\u9879", verb: "\u5305\u542B" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u8F93\u5165",
    email: "\u7535\u5B50\u90AE\u4EF6",
    url: "URL",
    emoji: "\u8868\u60C5\u7B26\u53F7",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO\u65E5\u671F\u65F6\u95F4",
    date: "ISO\u65E5\u671F",
    time: "ISO\u65F6\u95F4",
    duration: "ISO\u65F6\u957F",
    ipv4: "IPv4\u5730\u5740",
    ipv6: "IPv6\u5730\u5740",
    cidrv4: "IPv4\u7F51\u6BB5",
    cidrv6: "IPv6\u7F51\u6BB5",
    base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32",
    base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32",
    json_string: "JSON\u5B57\u7B26\u4E32",
    e164: "E.164\u53F7\u7801",
    jwt: "JWT",
    template_literal: "\u8F93\u5165"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u6570\u5B57",
    array: "\u6570\u7EC4",
    null: "\u7A7A\u503C(null)"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`;
        }
        return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`;
        return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`;
        return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`;
        if (_issue.format === "ends_with")
          return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`;
        if (_issue.format === "includes")
          return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`;
        return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`;
      case "unrecognized_keys":
        return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;
      case "invalid_union":
        return "\u65E0\u6548\u8F93\u5165";
      case "invalid_element":
        return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;
      default:
        return `\u65E0\u6548\u8F93\u5165`;
    }
  };
};
function zh_CN_default() {
  return {
    localeError: error48()
  };
}

// node_modules/zod/v4/locales/zh-TW.js
var error49 = () => {
  const Sizable = {
    string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" },
    file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" },
    array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" },
    set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u8F38\u5165",
    email: "\u90F5\u4EF6\u5730\u5740",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u65E5\u671F\u6642\u9593",
    date: "ISO \u65E5\u671F",
    time: "ISO \u6642\u9593",
    duration: "ISO \u671F\u9593",
    ipv4: "IPv4 \u4F4D\u5740",
    ipv6: "IPv6 \u4F4D\u5740",
    cidrv4: "IPv4 \u7BC4\u570D",
    cidrv6: "IPv6 \u7BC4\u570D",
    base64: "base64 \u7DE8\u78BC\u5B57\u4E32",
    base64url: "base64url \u7DE8\u78BC\u5B57\u4E32",
    json_string: "JSON \u5B57\u4E32",
    e164: "E.164 \u6578\u503C",
    jwt: "JWT",
    template_literal: "\u8F38\u5165"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`;
        }
        return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`;
        return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`;
        return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`;
        }
        if (_issue.format === "ends_with")
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`;
        if (_issue.format === "includes")
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`;
        return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`;
      case "unrecognized_keys":
        return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`;
      case "invalid_key":
        return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;
      case "invalid_union":
        return "\u7121\u6548\u7684\u8F38\u5165\u503C";
      case "invalid_element":
        return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;
      default:
        return `\u7121\u6548\u7684\u8F38\u5165\u503C`;
    }
  };
};
function zh_TW_default() {
  return {
    localeError: error49()
  };
}

// node_modules/zod/v4/locales/yo.js
var error50 = () => {
  const Sizable = {
    string: { unit: "\xE0mi", verb: "n\xED" },
    file: { unit: "bytes", verb: "n\xED" },
    array: { unit: "nkan", verb: "n\xED" },
    set: { unit: "nkan", verb: "n\xED" }
  };
  function getSizing(origin) {
    return Sizable[origin] ?? null;
  }
  const FormatDictionary = {
    regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",
    email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",
    url: "URL",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\xE0k\xF3k\xF2 ISO",
    date: "\u1ECDj\u1ECD\u0301 ISO",
    time: "\xE0k\xF3k\xF2 ISO",
    duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",
    ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",
    ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",
    cidrv4: "\xE0gb\xE8gb\xE8 IPv4",
    cidrv6: "\xE0gb\xE8gb\xE8 IPv6",
    base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",
    base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url",
    json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON",
    e164: "n\u1ECD\u0301mb\xE0 E.164",
    jwt: "JWT",
    template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "n\u1ECD\u0301mb\xE0",
    array: "akop\u1ECD"
  };
  return (issue2) => {
    switch (issue2.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`;
        }
        return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`;
        return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`;
        return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`;
        return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`;
        return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue2.format}`;
      }
      case "not_multiple_of":
        return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`;
      case "unrecognized_keys":
        return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;
      case "invalid_union":
        return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";
      case "invalid_element":
        return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;
      default:
        return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";
    }
  };
};
function yo_default() {
  return {
    localeError: error50()
  };
}

// node_modules/zod/v4/core/registries.js
var _a2;
var $output = /* @__PURE__ */ Symbol("ZodOutput");
var $input = /* @__PURE__ */ Symbol("ZodInput");
var $ZodRegistry = class {
  constructor() {
    this._map = /* @__PURE__ */ new WeakMap();
    this._idmap = /* @__PURE__ */ new Map();
  }
  add(schema, ..._meta) {
    const meta3 = _meta[0];
    this._map.set(schema, meta3);
    if (meta3 && typeof meta3 === "object" && "id" in meta3) {
      this._idmap.set(meta3.id, schema);
    }
    return this;
  }
  clear() {
    this._map = /* @__PURE__ */ new WeakMap();
    this._idmap = /* @__PURE__ */ new Map();
    return this;
  }
  remove(schema) {
    const meta3 = this._map.get(schema);
    if (meta3 && typeof meta3 === "object" && "id" in meta3) {
      this._idmap.delete(meta3.id);
    }
    this._map.delete(schema);
    return this;
  }
  get(schema) {
    const p = schema._zod.parent;
    if (p) {
      const pm = { ...this.get(p) ?? {} };
      delete pm.id;
      const f = { ...pm, ...this._map.get(schema) };
      return Object.keys(f).length ? f : void 0;
    }
    return this._map.get(schema);
  }
  has(schema) {
    return this._map.has(schema);
  }
};
function registry() {
  return new $ZodRegistry();
}
(_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
var globalRegistry = globalThis.__zod_globalRegistry;

// node_modules/zod/v4/core/api.js
// @__NO_SIDE_EFFECTS__
function _string(Class2, params) {
  return new Class2({
    type: "string",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedString(Class2, params) {
  return new Class2({
    type: "string",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _email(Class2, params) {
  return new Class2({
    type: "string",
    format: "email",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _guid(Class2, params) {
  return new Class2({
    type: "string",
    format: "guid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v4",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v6",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv7(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v7",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _url(Class2, params) {
  return new Class2({
    type: "string",
    format: "url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _emoji2(Class2, params) {
  return new Class2({
    type: "string",
    format: "emoji",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nanoid(Class2, params) {
  return new Class2({
    type: "string",
    format: "nanoid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "cuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cuid2(Class2, params) {
  return new Class2({
    type: "string",
    format: "cuid2",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ulid(Class2, params) {
  return new Class2({
    type: "string",
    format: "ulid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _xid(Class2, params) {
  return new Class2({
    type: "string",
    format: "xid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ksuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "ksuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ipv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "ipv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ipv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "ipv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _mac(Class2, params) {
  return new Class2({
    type: "string",
    format: "mac",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cidrv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "cidrv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cidrv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "cidrv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _base64(Class2, params) {
  return new Class2({
    type: "string",
    format: "base64",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _base64url(Class2, params) {
  return new Class2({
    type: "string",
    format: "base64url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _e164(Class2, params) {
  return new Class2({
    type: "string",
    format: "e164",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _jwt(Class2, params) {
  return new Class2({
    type: "string",
    format: "jwt",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
var TimePrecision = {
  Any: null,
  Minute: -1,
  Second: 0,
  Millisecond: 3,
  Microsecond: 6
};
// @__NO_SIDE_EFFECTS__
function _isoDateTime(Class2, params) {
  return new Class2({
    type: "string",
    format: "datetime",
    check: "string_format",
    offset: false,
    local: false,
    precision: null,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoDate(Class2, params) {
  return new Class2({
    type: "string",
    format: "date",
    check: "string_format",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoTime(Class2, params) {
  return new Class2({
    type: "string",
    format: "time",
    check: "string_format",
    precision: null,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoDuration(Class2, params) {
  return new Class2({
    type: "string",
    format: "duration",
    check: "string_format",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _number(Class2, params) {
  return new Class2({
    type: "number",
    checks: [],
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedNumber(Class2, params) {
  return new Class2({
    type: "number",
    coerce: true,
    checks: [],
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "safeint",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _float32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float32",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _float64(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float64",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "int32",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uint32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "uint32",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _boolean(Class2, params) {
  return new Class2({
    type: "boolean",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedBoolean(Class2, params) {
  return new Class2({
    type: "boolean",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _bigint(Class2, params) {
  return new Class2({
    type: "bigint",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedBigint(Class2, params) {
  return new Class2({
    type: "bigint",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int64(Class2, params) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "int64",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uint64(Class2, params) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "uint64",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _symbol(Class2, params) {
  return new Class2({
    type: "symbol",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _undefined2(Class2, params) {
  return new Class2({
    type: "undefined",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _null2(Class2, params) {
  return new Class2({
    type: "null",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _any(Class2) {
  return new Class2({
    type: "any"
  });
}
// @__NO_SIDE_EFFECTS__
function _unknown(Class2) {
  return new Class2({
    type: "unknown"
  });
}
// @__NO_SIDE_EFFECTS__
function _never(Class2, params) {
  return new Class2({
    type: "never",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _void(Class2, params) {
  return new Class2({
    type: "void",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _date(Class2, params) {
  return new Class2({
    type: "date",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedDate(Class2, params) {
  return new Class2({
    type: "date",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nan(Class2, params) {
  return new Class2({
    type: "nan",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _lt(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
// @__NO_SIDE_EFFECTS__
function _lte(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
// @__NO_SIDE_EFFECTS__
function _gt(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
// @__NO_SIDE_EFFECTS__
function _gte(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
// @__NO_SIDE_EFFECTS__
function _positive(params) {
  return /* @__PURE__ */ _gt(0, params);
}
// @__NO_SIDE_EFFECTS__
function _negative(params) {
  return /* @__PURE__ */ _lt(0, params);
}
// @__NO_SIDE_EFFECTS__
function _nonpositive(params) {
  return /* @__PURE__ */ _lte(0, params);
}
// @__NO_SIDE_EFFECTS__
function _nonnegative(params) {
  return /* @__PURE__ */ _gte(0, params);
}
// @__NO_SIDE_EFFECTS__
function _multipleOf(value, params) {
  return new $ZodCheckMultipleOf({
    check: "multiple_of",
    ...normalizeParams(params),
    value
  });
}
// @__NO_SIDE_EFFECTS__
function _maxSize(maximum, params) {
  return new $ZodCheckMaxSize({
    check: "max_size",
    ...normalizeParams(params),
    maximum
  });
}
// @__NO_SIDE_EFFECTS__
function _minSize(minimum, params) {
  return new $ZodCheckMinSize({
    check: "min_size",
    ...normalizeParams(params),
    minimum
  });
}
// @__NO_SIDE_EFFECTS__
function _size(size, params) {
  return new $ZodCheckSizeEquals({
    check: "size_equals",
    ...normalizeParams(params),
    size
  });
}
// @__NO_SIDE_EFFECTS__
function _maxLength(maximum, params) {
  const ch = new $ZodCheckMaxLength({
    check: "max_length",
    ...normalizeParams(params),
    maximum
  });
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _minLength(minimum, params) {
  return new $ZodCheckMinLength({
    check: "min_length",
    ...normalizeParams(params),
    minimum
  });
}
// @__NO_SIDE_EFFECTS__
function _length(length, params) {
  return new $ZodCheckLengthEquals({
    check: "length_equals",
    ...normalizeParams(params),
    length
  });
}
// @__NO_SIDE_EFFECTS__
function _regex(pattern, params) {
  return new $ZodCheckRegex({
    check: "string_format",
    format: "regex",
    ...normalizeParams(params),
    pattern
  });
}
// @__NO_SIDE_EFFECTS__
function _lowercase(params) {
  return new $ZodCheckLowerCase({
    check: "string_format",
    format: "lowercase",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uppercase(params) {
  return new $ZodCheckUpperCase({
    check: "string_format",
    format: "uppercase",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _includes(includes, params) {
  return new $ZodCheckIncludes({
    check: "string_format",
    format: "includes",
    ...normalizeParams(params),
    includes
  });
}
// @__NO_SIDE_EFFECTS__
function _startsWith(prefix, params) {
  return new $ZodCheckStartsWith({
    check: "string_format",
    format: "starts_with",
    ...normalizeParams(params),
    prefix
  });
}
// @__NO_SIDE_EFFECTS__
function _endsWith(suffix, params) {
  return new $ZodCheckEndsWith({
    check: "string_format",
    format: "ends_with",
    ...normalizeParams(params),
    suffix
  });
}
// @__NO_SIDE_EFFECTS__
function _property(property, schema, params) {
  return new $ZodCheckProperty({
    check: "property",
    property,
    schema,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _mime(types, params) {
  return new $ZodCheckMimeType({
    check: "mime_type",
    mime: types,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _overwrite(tx) {
  return new $ZodCheckOverwrite({
    check: "overwrite",
    tx
  });
}
// @__NO_SIDE_EFFECTS__
function _normalize(form) {
  return /* @__PURE__ */ _overwrite((input) => input.normalize(form));
}
// @__NO_SIDE_EFFECTS__
function _trim() {
  return /* @__PURE__ */ _overwrite((input) => input.trim());
}
// @__NO_SIDE_EFFECTS__
function _toLowerCase() {
  return /* @__PURE__ */ _overwrite((input) => input.toLowerCase());
}
// @__NO_SIDE_EFFECTS__
function _toUpperCase() {
  return /* @__PURE__ */ _overwrite((input) => input.toUpperCase());
}
// @__NO_SIDE_EFFECTS__
function _slugify() {
  return /* @__PURE__ */ _overwrite((input) => slugify(input));
}
// @__NO_SIDE_EFFECTS__
function _array(Class2, element, params) {
  return new Class2({
    type: "array",
    element,
    // get element() {
    //   return element;
    // },
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _union(Class2, options, params) {
  return new Class2({
    type: "union",
    options,
    ...normalizeParams(params)
  });
}
function _xor(Class2, options, params) {
  return new Class2({
    type: "union",
    options,
    inclusive: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _discriminatedUnion(Class2, discriminator, options, params) {
  return new Class2({
    type: "union",
    options,
    discriminator,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _intersection(Class2, left2, right2) {
  return new Class2({
    type: "intersection",
    left: left2,
    right: right2
  });
}
// @__NO_SIDE_EFFECTS__
function _tuple(Class2, items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new Class2({
    type: "tuple",
    items,
    rest,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _record(Class2, keyType, valueType, params) {
  return new Class2({
    type: "record",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _map(Class2, keyType, valueType, params) {
  return new Class2({
    type: "map",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _set(Class2, valueType, params) {
  return new Class2({
    type: "set",
    valueType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _enum(Class2, values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nativeEnum(Class2, entries, params) {
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _literal(Class2, value, params) {
  return new Class2({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _file(Class2, params) {
  return new Class2({
    type: "file",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _transform(Class2, fn) {
  return new Class2({
    type: "transform",
    transform: fn
  });
}
// @__NO_SIDE_EFFECTS__
function _optional(Class2, innerType) {
  return new Class2({
    type: "optional",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _nullable(Class2, innerType) {
  return new Class2({
    type: "nullable",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _default(Class2, innerType, defaultValue) {
  return new Class2({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
    }
  });
}
// @__NO_SIDE_EFFECTS__
function _nonoptional(Class2, innerType, params) {
  return new Class2({
    type: "nonoptional",
    innerType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _success(Class2, innerType) {
  return new Class2({
    type: "success",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _catch(Class2, innerType, catchValue) {
  return new Class2({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
// @__NO_SIDE_EFFECTS__
function _pipe(Class2, in_, out) {
  return new Class2({
    type: "pipe",
    in: in_,
    out
  });
}
// @__NO_SIDE_EFFECTS__
function _readonly(Class2, innerType) {
  return new Class2({
    type: "readonly",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _templateLiteral(Class2, parts, params) {
  return new Class2({
    type: "template_literal",
    parts,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _lazy(Class2, getter) {
  return new Class2({
    type: "lazy",
    getter
  });
}
// @__NO_SIDE_EFFECTS__
function _promise(Class2, innerType) {
  return new Class2({
    type: "promise",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _custom(Class2, fn, _params) {
  const norm = normalizeParams(_params);
  norm.abort ?? (norm.abort = true);
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...norm
  });
  return schema;
}
// @__NO_SIDE_EFFECTS__
function _refine(Class2, fn, _params) {
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...normalizeParams(_params)
  });
  return schema;
}
// @__NO_SIDE_EFFECTS__
function _superRefine(fn, params) {
  const ch = /* @__PURE__ */ _check((payload) => {
    payload.addIssue = (issue2) => {
      if (typeof issue2 === "string") {
        payload.issues.push(issue(issue2, payload.value, ch._zod.def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_issue.inst = ch);
        _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
        payload.issues.push(issue(_issue));
      }
    };
    return fn(payload.value, payload);
  }, params);
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _check(fn, params) {
  const ch = new $ZodCheck({
    check: "custom",
    ...normalizeParams(params)
  });
  ch._zod.check = fn;
  return ch;
}
// @__NO_SIDE_EFFECTS__
function describe(description) {
  const ch = new $ZodCheck({ check: "describe" });
  ch._zod.onattach = [
    (inst) => {
      const existing = globalRegistry.get(inst) ?? {};
      globalRegistry.add(inst, { ...existing, description });
    }
  ];
  ch._zod.check = () => {
  };
  return ch;
}
// @__NO_SIDE_EFFECTS__
function meta(metadata) {
  const ch = new $ZodCheck({ check: "meta" });
  ch._zod.onattach = [
    (inst) => {
      const existing = globalRegistry.get(inst) ?? {};
      globalRegistry.add(inst, { ...existing, ...metadata });
    }
  ];
  ch._zod.check = () => {
  };
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _stringbool(Classes, _params) {
  const params = normalizeParams(_params);
  let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"];
  let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"];
  if (params.case !== "sensitive") {
    truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
    falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
  }
  const truthySet = new Set(truthyArray);
  const falsySet = new Set(falsyArray);
  const _Codec = Classes.Codec ?? $ZodCodec;
  const _Boolean = Classes.Boolean ?? $ZodBoolean;
  const _String = Classes.String ?? $ZodString;
  const stringSchema = new _String({ type: "string", error: params.error });
  const booleanSchema = new _Boolean({ type: "boolean", error: params.error });
  const codec2 = new _Codec({
    type: "pipe",
    in: stringSchema,
    out: booleanSchema,
    transform: ((input, payload) => {
      let data = input;
      if (params.case !== "sensitive")
        data = data.toLowerCase();
      if (truthySet.has(data)) {
        return true;
      } else if (falsySet.has(data)) {
        return false;
      } else {
        payload.issues.push({
          code: "invalid_value",
          expected: "stringbool",
          values: [...truthySet, ...falsySet],
          input: payload.value,
          inst: codec2,
          continue: false
        });
        return {};
      }
    }),
    reverseTransform: ((input, _payload) => {
      if (input === true) {
        return truthyArray[0] || "true";
      } else {
        return falsyArray[0] || "false";
      }
    }),
    error: params.error
  });
  return codec2;
}
// @__NO_SIDE_EFFECTS__
function _stringFormat(Class2, format2, fnOrRegex, _params = {}) {
  const params = normalizeParams(_params);
  const def = {
    ...normalizeParams(_params),
    check: "string_format",
    type: "string",
    format: format2,
    fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
    ...params
  };
  if (fnOrRegex instanceof RegExp) {
    def.pattern = fnOrRegex;
  }
  const inst = new Class2(def);
  return inst;
}

// node_modules/zod/v4/core/to-json-schema.js
function initializeContext(params) {
  let target = params?.target ?? "draft-2020-12";
  if (target === "draft-4")
    target = "draft-04";
  if (target === "draft-7")
    target = "draft-07";
  return {
    processors: params.processors ?? {},
    metadataRegistry: params?.metadata ?? globalRegistry,
    target,
    unrepresentable: params?.unrepresentable ?? "throw",
    override: params?.override ?? (() => {
    }),
    io: params?.io ?? "output",
    counter: 0,
    seen: /* @__PURE__ */ new Map(),
    cycles: params?.cycles ?? "ref",
    reused: params?.reused ?? "inline",
    external: params?.external ?? void 0
  };
}
function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
  var _a3;
  const def = schema._zod.def;
  const seen = ctx.seen.get(schema);
  if (seen) {
    seen.count++;
    const isCycle = _params.schemaPath.includes(schema);
    if (isCycle) {
      seen.cycle = _params.path;
    }
    return seen.schema;
  }
  const result = { schema: {}, count: 1, cycle: void 0, path: _params.path };
  ctx.seen.set(schema, result);
  const overrideSchema = schema._zod.toJSONSchema?.();
  if (overrideSchema) {
    result.schema = overrideSchema;
  } else {
    const params = {
      ..._params,
      schemaPath: [..._params.schemaPath, schema],
      path: _params.path
    };
    if (schema._zod.processJSONSchema) {
      schema._zod.processJSONSchema(ctx, result.schema, params);
    } else {
      const _json = result.schema;
      const processor = ctx.processors[def.type];
      if (!processor) {
        throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
      }
      processor(schema, ctx, _json, params);
    }
    const parent = schema._zod.parent;
    if (parent) {
      if (!result.ref)
        result.ref = parent;
      process2(parent, ctx, params);
      ctx.seen.get(parent).isParent = true;
    }
  }
  const meta3 = ctx.metadataRegistry.get(schema);
  if (meta3)
    Object.assign(result.schema, meta3);
  if (ctx.io === "input" && isTransforming(schema)) {
    delete result.schema.examples;
    delete result.schema.default;
  }
  if (ctx.io === "input" && "_prefault" in result.schema)
    (_a3 = result.schema).default ?? (_a3.default = result.schema._prefault);
  delete result.schema._prefault;
  const _result = ctx.seen.get(schema);
  return _result.schema;
}
function extractDefs(ctx, schema) {
  const root2 = ctx.seen.get(schema);
  if (!root2)
    throw new Error("Unprocessed schema. This is a bug in Zod.");
  const idToSchema = /* @__PURE__ */ new Map();
  for (const entry of ctx.seen.entries()) {
    const id2 = ctx.metadataRegistry.get(entry[0])?.id;
    if (id2) {
      const existing = idToSchema.get(id2);
      if (existing && existing !== entry[0]) {
        throw new Error(`Duplicate schema id "${id2}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
      }
      idToSchema.set(id2, entry[0]);
    }
  }
  const makeURI = (entry) => {
    const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
    if (ctx.external) {
      const externalId = ctx.external.registry.get(entry[0])?.id;
      const uriGenerator = ctx.external.uri ?? ((id3) => id3);
      if (externalId) {
        return { ref: uriGenerator(externalId) };
      }
      const id2 = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
      entry[1].defId = id2;
      return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id2}` };
    }
    if (entry[1] === root2) {
      return { ref: "#" };
    }
    const uriPrefix = `#`;
    const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
    const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
    return { defId, ref: defUriPrefix + defId };
  };
  const extractToDef = (entry) => {
    if (entry[1].schema.$ref) {
      return;
    }
    const seen = entry[1];
    const { ref, defId } = makeURI(entry);
    seen.def = { ...seen.schema };
    if (defId)
      seen.defId = defId;
    const schema2 = seen.schema;
    for (const key in schema2) {
      delete schema2[key];
    }
    schema2.$ref = ref;
  };
  if (ctx.cycles === "throw") {
    for (const entry of ctx.seen.entries()) {
      const seen = entry[1];
      if (seen.cycle) {
        throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
      }
    }
  }
  for (const entry of ctx.seen.entries()) {
    const seen = entry[1];
    if (schema === entry[0]) {
      extractToDef(entry);
      continue;
    }
    if (ctx.external) {
      const ext = ctx.external.registry.get(entry[0])?.id;
      if (schema !== entry[0] && ext) {
        extractToDef(entry);
        continue;
      }
    }
    const id2 = ctx.metadataRegistry.get(entry[0])?.id;
    if (id2) {
      extractToDef(entry);
      continue;
    }
    if (seen.cycle) {
      extractToDef(entry);
      continue;
    }
    if (seen.count > 1) {
      if (ctx.reused === "ref") {
        extractToDef(entry);
        continue;
      }
    }
  }
}
function finalize(ctx, schema) {
  const root2 = ctx.seen.get(schema);
  if (!root2)
    throw new Error("Unprocessed schema. This is a bug in Zod.");
  const flattenRef = (zodSchema) => {
    const seen = ctx.seen.get(zodSchema);
    if (seen.ref === null)
      return;
    const schema2 = seen.def ?? seen.schema;
    const _cached = { ...schema2 };
    const ref = seen.ref;
    seen.ref = null;
    if (ref) {
      flattenRef(ref);
      const refSeen = ctx.seen.get(ref);
      const refSchema = refSeen.schema;
      if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
        schema2.allOf = schema2.allOf ?? [];
        schema2.allOf.push(refSchema);
      } else {
        Object.assign(schema2, refSchema);
      }
      Object.assign(schema2, _cached);
      const isParentRef = zodSchema._zod.parent === ref;
      if (isParentRef) {
        for (const key in schema2) {
          if (key === "$ref" || key === "allOf")
            continue;
          if (!(key in _cached)) {
            delete schema2[key];
          }
        }
      }
      if (refSchema.$ref && refSeen.def) {
        for (const key in schema2) {
          if (key === "$ref" || key === "allOf")
            continue;
          if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) {
            delete schema2[key];
          }
        }
      }
    }
    const parent = zodSchema._zod.parent;
    if (parent && parent !== ref) {
      flattenRef(parent);
      const parentSeen = ctx.seen.get(parent);
      if (parentSeen?.schema.$ref) {
        schema2.$ref = parentSeen.schema.$ref;
        if (parentSeen.def) {
          for (const key in schema2) {
            if (key === "$ref" || key === "allOf")
              continue;
            if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) {
              delete schema2[key];
            }
          }
        }
      }
    }
    ctx.override({
      zodSchema,
      jsonSchema: schema2,
      path: seen.path ?? []
    });
  };
  for (const entry of [...ctx.seen.entries()].reverse()) {
    flattenRef(entry[0]);
  }
  const result = {};
  if (ctx.target === "draft-2020-12") {
    result.$schema = "https://json-schema.org/draft/2020-12/schema";
  } else if (ctx.target === "draft-07") {
    result.$schema = "http://json-schema.org/draft-07/schema#";
  } else if (ctx.target === "draft-04") {
    result.$schema = "http://json-schema.org/draft-04/schema#";
  } else if (ctx.target === "openapi-3.0") {
  } else {
  }
  if (ctx.external?.uri) {
    const id2 = ctx.external.registry.get(schema)?.id;
    if (!id2)
      throw new Error("Schema is missing an `id` property");
    result.$id = ctx.external.uri(id2);
  }
  Object.assign(result, root2.def ?? root2.schema);
  const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
  if (rootMetaId !== void 0 && result.id === rootMetaId)
    delete result.id;
  const defs = ctx.external?.defs ?? {};
  for (const entry of ctx.seen.entries()) {
    const seen = entry[1];
    if (seen.def && seen.defId) {
      if (seen.def.id === seen.defId)
        delete seen.def.id;
      defs[seen.defId] = seen.def;
    }
  }
  if (ctx.external) {
  } else {
    if (Object.keys(defs).length > 0) {
      if (ctx.target === "draft-2020-12") {
        result.$defs = defs;
      } else {
        result.definitions = defs;
      }
    }
  }
  try {
    const finalized = JSON.parse(JSON.stringify(result));
    Object.defineProperty(finalized, "~standard", {
      value: {
        ...schema["~standard"],
        jsonSchema: {
          input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
          output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
        }
      },
      enumerable: false,
      writable: false
    });
    return finalized;
  } catch (_err) {
    throw new Error("Error converting schema to JSON.");
  }
}
function isTransforming(_schema, _ctx) {
  const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
  if (ctx.seen.has(_schema))
    return false;
  ctx.seen.add(_schema);
  const def = _schema._zod.def;
  if (def.type === "transform")
    return true;
  if (def.type === "array")
    return isTransforming(def.element, ctx);
  if (def.type === "set")
    return isTransforming(def.valueType, ctx);
  if (def.type === "lazy")
    return isTransforming(def.getter(), ctx);
  if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") {
    return isTransforming(def.innerType, ctx);
  }
  if (def.type === "intersection") {
    return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
  }
  if (def.type === "record" || def.type === "map") {
    return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
  }
  if (def.type === "pipe") {
    if (_schema._zod.traits.has("$ZodCodec"))
      return true;
    return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
  }
  if (def.type === "object") {
    for (const key in def.shape) {
      if (isTransforming(def.shape[key], ctx))
        return true;
    }
    return false;
  }
  if (def.type === "union") {
    for (const option of def.options) {
      if (isTransforming(option, ctx))
        return true;
    }
    return false;
  }
  if (def.type === "tuple") {
    for (const item of def.items) {
      if (isTransforming(item, ctx))
        return true;
    }
    if (def.rest && isTransforming(def.rest, ctx))
      return true;
    return false;
  }
  return false;
}
var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
  const ctx = initializeContext({ ...params, processors });
  process2(schema, ctx);
  extractDefs(ctx, schema);
  return finalize(ctx, schema);
};
var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
  const { libraryOptions, target } = params ?? {};
  const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors });
  process2(schema, ctx);
  extractDefs(ctx, schema);
  return finalize(ctx, schema);
};

// node_modules/zod/v4/core/json-schema-processors.js
var formatMap = {
  guid: "uuid",
  url: "uri",
  datetime: "date-time",
  json_string: "json-string",
  regex: ""
  // do not set
};
var stringProcessor = (schema, ctx, _json, _params) => {
  const json2 = _json;
  json2.type = "string";
  const { minimum, maximum, format: format2, patterns, contentEncoding } = schema._zod.bag;
  if (typeof minimum === "number")
    json2.minLength = minimum;
  if (typeof maximum === "number")
    json2.maxLength = maximum;
  if (format2) {
    json2.format = formatMap[format2] ?? format2;
    if (json2.format === "")
      delete json2.format;
    if (format2 === "time") {
      delete json2.format;
    }
  }
  if (contentEncoding)
    json2.contentEncoding = contentEncoding;
  if (patterns && patterns.size > 0) {
    const regexes = [...patterns];
    if (regexes.length === 1)
      json2.pattern = regexes[0].source;
    else if (regexes.length > 1) {
      json2.allOf = [
        ...regexes.map((regex) => ({
          ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
          pattern: regex.source
        }))
      ];
    }
  }
};
var numberProcessor = (schema, ctx, _json, _params) => {
  const json2 = _json;
  const { minimum, maximum, format: format2, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
  if (typeof format2 === "string" && format2.includes("int"))
    json2.type = "integer";
  else
    json2.type = "number";
  const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
  const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
  const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
  if (exMin) {
    if (legacy) {
      json2.minimum = exclusiveMinimum;
      json2.exclusiveMinimum = true;
    } else {
      json2.exclusiveMinimum = exclusiveMinimum;
    }
  } else if (typeof minimum === "number") {
    json2.minimum = minimum;
  }
  if (exMax) {
    if (legacy) {
      json2.maximum = exclusiveMaximum;
      json2.exclusiveMaximum = true;
    } else {
      json2.exclusiveMaximum = exclusiveMaximum;
    }
  } else if (typeof maximum === "number") {
    json2.maximum = maximum;
  }
  if (typeof multipleOf === "number")
    json2.multipleOf = multipleOf;
};
var booleanProcessor = (_schema, _ctx, json2, _params) => {
  json2.type = "boolean";
};
var bigintProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("BigInt cannot be represented in JSON Schema");
  }
};
var symbolProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Symbols cannot be represented in JSON Schema");
  }
};
var nullProcessor = (_schema, ctx, json2, _params) => {
  if (ctx.target === "openapi-3.0") {
    json2.type = "string";
    json2.nullable = true;
    json2.enum = [null];
  } else {
    json2.type = "null";
  }
};
var undefinedProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Undefined cannot be represented in JSON Schema");
  }
};
var voidProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Void cannot be represented in JSON Schema");
  }
};
var neverProcessor = (_schema, _ctx, json2, _params) => {
  json2.not = {};
};
var anyProcessor = (_schema, _ctx, _json, _params) => {
};
var unknownProcessor = (_schema, _ctx, _json, _params) => {
};
var dateProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Date cannot be represented in JSON Schema");
  }
};
var enumProcessor = (schema, _ctx, json2, _params) => {
  const def = schema._zod.def;
  const values = getEnumValues(def.entries);
  if (values.every((v) => typeof v === "number"))
    json2.type = "number";
  if (values.every((v) => typeof v === "string"))
    json2.type = "string";
  json2.enum = values;
};
var literalProcessor = (schema, ctx, json2, _params) => {
  const def = schema._zod.def;
  const vals = [];
  for (const val of def.values) {
    if (val === void 0) {
      if (ctx.unrepresentable === "throw") {
        throw new Error("Literal `undefined` cannot be represented in JSON Schema");
      } else {
      }
    } else if (typeof val === "bigint") {
      if (ctx.unrepresentable === "throw") {
        throw new Error("BigInt literals cannot be represented in JSON Schema");
      } else {
        vals.push(Number(val));
      }
    } else {
      vals.push(val);
    }
  }
  if (vals.length === 0) {
  } else if (vals.length === 1) {
    const val = vals[0];
    json2.type = val === null ? "null" : typeof val;
    if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
      json2.enum = [val];
    } else {
      json2.const = val;
    }
  } else {
    if (vals.every((v) => typeof v === "number"))
      json2.type = "number";
    if (vals.every((v) => typeof v === "string"))
      json2.type = "string";
    if (vals.every((v) => typeof v === "boolean"))
      json2.type = "boolean";
    if (vals.every((v) => v === null))
      json2.type = "null";
    json2.enum = vals;
  }
};
var nanProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("NaN cannot be represented in JSON Schema");
  }
};
var templateLiteralProcessor = (schema, _ctx, json2, _params) => {
  const _json = json2;
  const pattern = schema._zod.pattern;
  if (!pattern)
    throw new Error("Pattern not found in template literal");
  _json.type = "string";
  _json.pattern = pattern.source;
};
var fileProcessor = (schema, _ctx, json2, _params) => {
  const _json = json2;
  const file2 = {
    type: "string",
    format: "binary",
    contentEncoding: "binary"
  };
  const { minimum, maximum, mime } = schema._zod.bag;
  if (minimum !== void 0)
    file2.minLength = minimum;
  if (maximum !== void 0)
    file2.maxLength = maximum;
  if (mime) {
    if (mime.length === 1) {
      file2.contentMediaType = mime[0];
      Object.assign(_json, file2);
    } else {
      Object.assign(_json, file2);
      _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
    }
  } else {
    Object.assign(_json, file2);
  }
};
var successProcessor = (_schema, _ctx, json2, _params) => {
  json2.type = "boolean";
};
var customProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Custom types cannot be represented in JSON Schema");
  }
};
var functionProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Function types cannot be represented in JSON Schema");
  }
};
var transformProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Transforms cannot be represented in JSON Schema");
  }
};
var mapProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Map cannot be represented in JSON Schema");
  }
};
var setProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Set cannot be represented in JSON Schema");
  }
};
var arrayProcessor = (schema, ctx, _json, params) => {
  const json2 = _json;
  const def = schema._zod.def;
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json2.minItems = minimum;
  if (typeof maximum === "number")
    json2.maxItems = maximum;
  json2.type = "array";
  json2.items = process2(def.element, ctx, {
    ...params,
    path: [...params.path, "items"]
  });
};
var objectProcessor = (schema, ctx, _json, params) => {
  const json2 = _json;
  const def = schema._zod.def;
  json2.type = "object";
  json2.properties = {};
  const shape = def.shape;
  for (const key in shape) {
    json2.properties[key] = process2(shape[key], ctx, {
      ...params,
      path: [...params.path, "properties", key]
    });
  }
  const allKeys = new Set(Object.keys(shape));
  const requiredKeys = new Set([...allKeys].filter((key) => {
    const v = def.shape[key]._zod;
    if (ctx.io === "input") {
      return v.optin === void 0;
    } else {
      return v.optout === void 0;
    }
  }));
  if (requiredKeys.size > 0) {
    json2.required = Array.from(requiredKeys);
  }
  if (def.catchall?._zod.def.type === "never") {
    json2.additionalProperties = false;
  } else if (!def.catchall) {
    if (ctx.io === "output")
      json2.additionalProperties = false;
  } else if (def.catchall) {
    json2.additionalProperties = process2(def.catchall, ctx, {
      ...params,
      path: [...params.path, "additionalProperties"]
    });
  }
};
var unionProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  const isExclusive = def.inclusive === false;
  const options = def.options.map((x2, i) => process2(x2, ctx, {
    ...params,
    path: [...params.path, isExclusive ? "oneOf" : "anyOf", i]
  }));
  if (isExclusive) {
    json2.oneOf = options;
  } else {
    json2.anyOf = options;
  }
};
var intersectionProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  const a = process2(def.left, ctx, {
    ...params,
    path: [...params.path, "allOf", 0]
  });
  const b = process2(def.right, ctx, {
    ...params,
    path: [...params.path, "allOf", 1]
  });
  const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
  const allOf = [
    ...isSimpleIntersection(a) ? a.allOf : [a],
    ...isSimpleIntersection(b) ? b.allOf : [b]
  ];
  json2.allOf = allOf;
};
var tupleProcessor = (schema, ctx, _json, params) => {
  const json2 = _json;
  const def = schema._zod.def;
  json2.type = "array";
  const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
  const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
  const prefixItems = def.items.map((x2, i) => process2(x2, ctx, {
    ...params,
    path: [...params.path, prefixPath, i]
  }));
  const rest = def.rest ? process2(def.rest, ctx, {
    ...params,
    path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []]
  }) : null;
  if (ctx.target === "draft-2020-12") {
    json2.prefixItems = prefixItems;
    if (rest) {
      json2.items = rest;
    }
  } else if (ctx.target === "openapi-3.0") {
    json2.items = {
      anyOf: prefixItems
    };
    if (rest) {
      json2.items.anyOf.push(rest);
    }
    json2.minItems = prefixItems.length;
    if (!rest) {
      json2.maxItems = prefixItems.length;
    }
  } else {
    json2.items = prefixItems;
    if (rest) {
      json2.additionalItems = rest;
    }
  }
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json2.minItems = minimum;
  if (typeof maximum === "number")
    json2.maxItems = maximum;
};
var recordProcessor = (schema, ctx, _json, params) => {
  const json2 = _json;
  const def = schema._zod.def;
  json2.type = "object";
  const keyType = def.keyType;
  const keyBag = keyType._zod.bag;
  const patterns = keyBag?.patterns;
  if (def.mode === "loose" && patterns && patterns.size > 0) {
    const valueSchema = process2(def.valueType, ctx, {
      ...params,
      path: [...params.path, "patternProperties", "*"]
    });
    json2.patternProperties = {};
    for (const pattern of patterns) {
      json2.patternProperties[pattern.source] = valueSchema;
    }
  } else {
    if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
      json2.propertyNames = process2(def.keyType, ctx, {
        ...params,
        path: [...params.path, "propertyNames"]
      });
    }
    json2.additionalProperties = process2(def.valueType, ctx, {
      ...params,
      path: [...params.path, "additionalProperties"]
    });
  }
  const keyValues = keyType._zod.values;
  if (keyValues) {
    const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
    if (validKeyValues.length > 0) {
      json2.required = validKeyValues;
    }
  }
};
var nullableProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  const inner = process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  if (ctx.target === "openapi-3.0") {
    seen.ref = def.innerType;
    json2.nullable = true;
  } else {
    json2.anyOf = [inner, { type: "null" }];
  }
};
var nonoptionalProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var defaultProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json2.default = JSON.parse(JSON.stringify(def.defaultValue));
};
var prefaultProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  if (ctx.io === "input")
    json2._prefault = JSON.parse(JSON.stringify(def.defaultValue));
};
var catchProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  let catchValue;
  try {
    catchValue = def.catchValue(void 0);
  } catch {
    throw new Error("Dynamic catch values are not supported in JSON Schema");
  }
  json2.default = catchValue;
};
var pipeProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  const inIsTransform = def.in._zod.traits.has("$ZodTransform");
  const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
  process2(innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
};
var readonlyProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json2.readOnly = true;
};
var promiseProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var optionalProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var lazyProcessor = (schema, ctx, _json, params) => {
  const innerType = schema._zod.innerType;
  process2(innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
};
var allProcessors = {
  string: stringProcessor,
  number: numberProcessor,
  boolean: booleanProcessor,
  bigint: bigintProcessor,
  symbol: symbolProcessor,
  null: nullProcessor,
  undefined: undefinedProcessor,
  void: voidProcessor,
  never: neverProcessor,
  any: anyProcessor,
  unknown: unknownProcessor,
  date: dateProcessor,
  enum: enumProcessor,
  literal: literalProcessor,
  nan: nanProcessor,
  template_literal: templateLiteralProcessor,
  file: fileProcessor,
  success: successProcessor,
  custom: customProcessor,
  function: functionProcessor,
  transform: transformProcessor,
  map: mapProcessor,
  set: setProcessor,
  array: arrayProcessor,
  object: objectProcessor,
  union: unionProcessor,
  intersection: intersectionProcessor,
  tuple: tupleProcessor,
  record: recordProcessor,
  nullable: nullableProcessor,
  nonoptional: nonoptionalProcessor,
  default: defaultProcessor,
  prefault: prefaultProcessor,
  catch: catchProcessor,
  pipe: pipeProcessor,
  readonly: readonlyProcessor,
  promise: promiseProcessor,
  optional: optionalProcessor,
  lazy: lazyProcessor
};
function toJSONSchema(input, params) {
  if ("_idmap" in input) {
    const registry2 = input;
    const ctx2 = initializeContext({ ...params, processors: allProcessors });
    const defs = {};
    for (const entry of registry2._idmap.entries()) {
      const [_, schema] = entry;
      process2(schema, ctx2);
    }
    const schemas = {};
    const external = {
      registry: registry2,
      uri: params?.uri,
      defs
    };
    ctx2.external = external;
    for (const entry of registry2._idmap.entries()) {
      const [key, schema] = entry;
      extractDefs(ctx2, schema);
      schemas[key] = finalize(ctx2, schema);
    }
    if (Object.keys(defs).length > 0) {
      const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions";
      schemas.__shared = {
        [defsSegment]: defs
      };
    }
    return { schemas };
  }
  const ctx = initializeContext({ ...params, processors: allProcessors });
  process2(input, ctx);
  extractDefs(ctx, input);
  return finalize(ctx, input);
}

// node_modules/zod/v4/core/json-schema-generator.js
var JSONSchemaGenerator = class {
  /** @deprecated Access via ctx instead */
  get metadataRegistry() {
    return this.ctx.metadataRegistry;
  }
  /** @deprecated Access via ctx instead */
  get target() {
    return this.ctx.target;
  }
  /** @deprecated Access via ctx instead */
  get unrepresentable() {
    return this.ctx.unrepresentable;
  }
  /** @deprecated Access via ctx instead */
  get override() {
    return this.ctx.override;
  }
  /** @deprecated Access via ctx instead */
  get io() {
    return this.ctx.io;
  }
  /** @deprecated Access via ctx instead */
  get counter() {
    return this.ctx.counter;
  }
  set counter(value) {
    this.ctx.counter = value;
  }
  /** @deprecated Access via ctx instead */
  get seen() {
    return this.ctx.seen;
  }
  constructor(params) {
    let normalizedTarget = params?.target ?? "draft-2020-12";
    if (normalizedTarget === "draft-4")
      normalizedTarget = "draft-04";
    if (normalizedTarget === "draft-7")
      normalizedTarget = "draft-07";
    this.ctx = initializeContext({
      processors: allProcessors,
      target: normalizedTarget,
      ...params?.metadata && { metadata: params.metadata },
      ...params?.unrepresentable && { unrepresentable: params.unrepresentable },
      ...params?.override && { override: params.override },
      ...params?.io && { io: params.io }
    });
  }
  /**
   * Process a schema to prepare it for JSON Schema generation.
   * This must be called before emit().
   */
  process(schema, _params = { path: [], schemaPath: [] }) {
    return process2(schema, this.ctx, _params);
  }
  /**
   * Emit the final JSON Schema after processing.
   * Must call process() first.
   */
  emit(schema, _params) {
    if (_params) {
      if (_params.cycles)
        this.ctx.cycles = _params.cycles;
      if (_params.reused)
        this.ctx.reused = _params.reused;
      if (_params.external)
        this.ctx.external = _params.external;
    }
    extractDefs(this.ctx, schema);
    const result = finalize(this.ctx, schema);
    const { "~standard": _, ...plainResult } = result;
    return plainResult;
  }
};

// node_modules/zod/v4/core/json-schema.js
var json_schema_exports = {};

// node_modules/zod/v4/classic/schemas.js
var schemas_exports2 = {};
__export(schemas_exports2, {
  ZodAny: () => ZodAny,
  ZodArray: () => ZodArray,
  ZodBase64: () => ZodBase64,
  ZodBase64URL: () => ZodBase64URL,
  ZodBigInt: () => ZodBigInt,
  ZodBigIntFormat: () => ZodBigIntFormat,
  ZodBoolean: () => ZodBoolean,
  ZodCIDRv4: () => ZodCIDRv4,
  ZodCIDRv6: () => ZodCIDRv6,
  ZodCUID: () => ZodCUID,
  ZodCUID2: () => ZodCUID2,
  ZodCatch: () => ZodCatch,
  ZodCodec: () => ZodCodec,
  ZodCustom: () => ZodCustom,
  ZodCustomStringFormat: () => ZodCustomStringFormat,
  ZodDate: () => ZodDate,
  ZodDefault: () => ZodDefault,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodE164: () => ZodE164,
  ZodEmail: () => ZodEmail,
  ZodEmoji: () => ZodEmoji,
  ZodEnum: () => ZodEnum,
  ZodExactOptional: () => ZodExactOptional,
  ZodFile: () => ZodFile,
  ZodFunction: () => ZodFunction,
  ZodGUID: () => ZodGUID,
  ZodIPv4: () => ZodIPv4,
  ZodIPv6: () => ZodIPv6,
  ZodIntersection: () => ZodIntersection,
  ZodJWT: () => ZodJWT,
  ZodKSUID: () => ZodKSUID,
  ZodLazy: () => ZodLazy,
  ZodLiteral: () => ZodLiteral,
  ZodMAC: () => ZodMAC,
  ZodMap: () => ZodMap,
  ZodNaN: () => ZodNaN,
  ZodNanoID: () => ZodNanoID,
  ZodNever: () => ZodNever,
  ZodNonOptional: () => ZodNonOptional,
  ZodNull: () => ZodNull,
  ZodNullable: () => ZodNullable,
  ZodNumber: () => ZodNumber,
  ZodNumberFormat: () => ZodNumberFormat,
  ZodObject: () => ZodObject,
  ZodOptional: () => ZodOptional,
  ZodPipe: () => ZodPipe,
  ZodPrefault: () => ZodPrefault,
  ZodPreprocess: () => ZodPreprocess,
  ZodPromise: () => ZodPromise,
  ZodReadonly: () => ZodReadonly,
  ZodRecord: () => ZodRecord,
  ZodSet: () => ZodSet,
  ZodString: () => ZodString,
  ZodStringFormat: () => ZodStringFormat,
  ZodSuccess: () => ZodSuccess,
  ZodSymbol: () => ZodSymbol,
  ZodTemplateLiteral: () => ZodTemplateLiteral,
  ZodTransform: () => ZodTransform,
  ZodTuple: () => ZodTuple,
  ZodType: () => ZodType,
  ZodULID: () => ZodULID,
  ZodURL: () => ZodURL,
  ZodUUID: () => ZodUUID,
  ZodUndefined: () => ZodUndefined,
  ZodUnion: () => ZodUnion,
  ZodUnknown: () => ZodUnknown,
  ZodVoid: () => ZodVoid,
  ZodXID: () => ZodXID,
  ZodXor: () => ZodXor,
  _ZodString: () => _ZodString,
  _default: () => _default2,
  _function: () => _function,
  any: () => any,
  array: () => array2,
  base64: () => base642,
  base64url: () => base64url2,
  bigint: () => bigint2,
  boolean: () => boolean2,
  catch: () => _catch2,
  check: () => check,
  cidrv4: () => cidrv42,
  cidrv6: () => cidrv62,
  codec: () => codec,
  cuid: () => cuid3,
  cuid2: () => cuid22,
  custom: () => custom,
  date: () => date4,
  describe: () => describe2,
  discriminatedUnion: () => discriminatedUnion,
  e164: () => e1642,
  email: () => email2,
  emoji: () => emoji2,
  enum: () => _enum2,
  exactOptional: () => exactOptional,
  file: () => file,
  float32: () => float32,
  float64: () => float64,
  function: () => _function,
  guid: () => guid2,
  hash: () => hash,
  hex: () => hex3,
  hostname: () => hostname2,
  httpUrl: () => httpUrl,
  instanceof: () => _instanceof,
  int: () => int2,
  int32: () => int32,
  int64: () => int64,
  intersection: () => intersection,
  invertCodec: () => invertCodec,
  ipv4: () => ipv42,
  ipv6: () => ipv62,
  json: () => json,
  jwt: () => jwt,
  keyof: () => keyof,
  ksuid: () => ksuid2,
  lazy: () => lazy,
  literal: () => literal,
  looseObject: () => looseObject,
  looseRecord: () => looseRecord,
  mac: () => mac2,
  map: () => map3,
  meta: () => meta2,
  nan: () => nan,
  nanoid: () => nanoid2,
  nativeEnum: () => nativeEnum,
  never: () => never,
  nonoptional: () => nonoptional,
  null: () => _null3,
  nullable: () => nullable,
  nullish: () => nullish2,
  number: () => number6,
  object: () => object,
  optional: () => optional,
  partialRecord: () => partialRecord,
  pipe: () => pipe,
  prefault: () => prefault,
  preprocess: () => preprocess,
  promise: () => promise,
  readonly: () => readonly,
  record: () => record,
  refine: () => refine,
  set: () => set3,
  strictObject: () => strictObject,
  string: () => string2,
  stringFormat: () => stringFormat,
  stringbool: () => stringbool,
  success: () => success,
  superRefine: () => superRefine,
  symbol: () => symbol,
  templateLiteral: () => templateLiteral,
  transform: () => transform,
  tuple: () => tuple,
  uint32: () => uint32,
  uint64: () => uint64,
  ulid: () => ulid2,
  undefined: () => _undefined3,
  union: () => union,
  unknown: () => unknown,
  url: () => url,
  uuid: () => uuid2,
  uuidv4: () => uuidv4,
  uuidv6: () => uuidv6,
  uuidv7: () => uuidv7,
  void: () => _void2,
  xid: () => xid2,
  xor: () => xor
});

// node_modules/zod/v4/classic/checks.js
var checks_exports2 = {};
__export(checks_exports2, {
  endsWith: () => _endsWith,
  gt: () => _gt,
  gte: () => _gte,
  includes: () => _includes,
  length: () => _length,
  lowercase: () => _lowercase,
  lt: () => _lt,
  lte: () => _lte,
  maxLength: () => _maxLength,
  maxSize: () => _maxSize,
  mime: () => _mime,
  minLength: () => _minLength,
  minSize: () => _minSize,
  multipleOf: () => _multipleOf,
  negative: () => _negative,
  nonnegative: () => _nonnegative,
  nonpositive: () => _nonpositive,
  normalize: () => _normalize,
  overwrite: () => _overwrite,
  positive: () => _positive,
  property: () => _property,
  regex: () => _regex,
  size: () => _size,
  slugify: () => _slugify,
  startsWith: () => _startsWith,
  toLowerCase: () => _toLowerCase,
  toUpperCase: () => _toUpperCase,
  trim: () => _trim,
  uppercase: () => _uppercase
});

// node_modules/zod/v4/classic/iso.js
var iso_exports = {};
__export(iso_exports, {
  ZodISODate: () => ZodISODate,
  ZodISODateTime: () => ZodISODateTime,
  ZodISODuration: () => ZodISODuration,
  ZodISOTime: () => ZodISOTime,
  date: () => date3,
  datetime: () => datetime2,
  duration: () => duration2,
  time: () => time2
});
var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
  $ZodISODateTime.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function datetime2(params) {
  return _isoDateTime(ZodISODateTime, params);
}
var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
  $ZodISODate.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function date3(params) {
  return _isoDate(ZodISODate, params);
}
var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
  $ZodISOTime.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function time2(params) {
  return _isoTime(ZodISOTime, params);
}
var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
  $ZodISODuration.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function duration2(params) {
  return _isoDuration(ZodISODuration, params);
}

// node_modules/zod/v4/classic/errors.js
var initializer2 = (inst, issues) => {
  $ZodError.init(inst, issues);
  inst.name = "ZodError";
  Object.defineProperties(inst, {
    format: {
      value: (mapper) => formatError(inst, mapper)
      // enumerable: false,
    },
    flatten: {
      value: (mapper) => flattenError(inst, mapper)
      // enumerable: false,
    },
    addIssue: {
      value: (issue2) => {
        inst.issues.push(issue2);
        inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
      }
      // enumerable: false,
    },
    addIssues: {
      value: (issues2) => {
        inst.issues.push(...issues2);
        inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
      }
      // enumerable: false,
    },
    isEmpty: {
      get() {
        return inst.issues.length === 0;
      }
      // enumerable: false,
    }
  });
};
var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2);
var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, {
  Parent: Error
});

// node_modules/zod/v4/classic/parse.js
var parse4 = /* @__PURE__ */ _parse(ZodRealError);
var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
var encode2 = /* @__PURE__ */ _encode(ZodRealError);
var decode2 = /* @__PURE__ */ _decode(ZodRealError);
var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError);
var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError);
var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError);
var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError);
var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);

// node_modules/zod/v4/classic/schemas.js
var _installedGroups = /* @__PURE__ */ new WeakMap();
function _installLazyMethods(inst, group, methods) {
  const proto = Object.getPrototypeOf(inst);
  let installed = _installedGroups.get(proto);
  if (!installed) {
    installed = /* @__PURE__ */ new Set();
    _installedGroups.set(proto, installed);
  }
  if (installed.has(group))
    return;
  installed.add(group);
  for (const key in methods) {
    const fn = methods[key];
    Object.defineProperty(proto, key, {
      configurable: true,
      enumerable: false,
      get() {
        const bound = fn.bind(this);
        Object.defineProperty(this, key, {
          configurable: true,
          writable: true,
          enumerable: true,
          value: bound
        });
        return bound;
      },
      set(v) {
        Object.defineProperty(this, key, {
          configurable: true,
          writable: true,
          enumerable: true,
          value: v
        });
      }
    });
  }
}
var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
  $ZodType.init(inst, def);
  Object.assign(inst["~standard"], {
    jsonSchema: {
      input: createStandardJSONSchemaMethod(inst, "input"),
      output: createStandardJSONSchemaMethod(inst, "output")
    }
  });
  inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
  inst.def = def;
  inst.type = def.type;
  Object.defineProperty(inst, "_def", { value: def });
  inst.parse = (data, params) => parse4(inst, data, params, { callee: inst.parse });
  inst.safeParse = (data, params) => safeParse2(inst, data, params);
  inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
  inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
  inst.spa = inst.safeParseAsync;
  inst.encode = (data, params) => encode2(inst, data, params);
  inst.decode = (data, params) => decode2(inst, data, params);
  inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params);
  inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params);
  inst.safeEncode = (data, params) => safeEncode2(inst, data, params);
  inst.safeDecode = (data, params) => safeDecode2(inst, data, params);
  inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params);
  inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params);
  _installLazyMethods(inst, "ZodType", {
    check(...chks) {
      const def2 = this.def;
      return this.clone(util_exports2.mergeDefs(def2, {
        checks: [
          ...def2.checks ?? [],
          ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
        ]
      }), { parent: true });
    },
    with(...chks) {
      return this.check(...chks);
    },
    clone(def2, params) {
      return clone2(this, def2, params);
    },
    brand() {
      return this;
    },
    register(reg, meta3) {
      reg.add(this, meta3);
      return this;
    },
    refine(check2, params) {
      return this.check(refine(check2, params));
    },
    superRefine(refinement, params) {
      return this.check(superRefine(refinement, params));
    },
    overwrite(fn) {
      return this.check(_overwrite(fn));
    },
    optional() {
      return optional(this);
    },
    exactOptional() {
      return exactOptional(this);
    },
    nullable() {
      return nullable(this);
    },
    nullish() {
      return optional(nullable(this));
    },
    nonoptional(params) {
      return nonoptional(this, params);
    },
    array() {
      return array2(this);
    },
    or(arg) {
      return union([this, arg]);
    },
    and(arg) {
      return intersection(this, arg);
    },
    transform(tx) {
      return pipe(this, transform(tx));
    },
    default(d) {
      return _default2(this, d);
    },
    prefault(d) {
      return prefault(this, d);
    },
    catch(params) {
      return _catch2(this, params);
    },
    pipe(target) {
      return pipe(this, target);
    },
    readonly() {
      return readonly(this);
    },
    describe(description) {
      const cl = this.clone();
      globalRegistry.add(cl, { description });
      return cl;
    },
    meta(...args) {
      if (args.length === 0)
        return globalRegistry.get(this);
      const cl = this.clone();
      globalRegistry.add(cl, args[0]);
      return cl;
    },
    isOptional() {
      return this.safeParse(void 0).success;
    },
    isNullable() {
      return this.safeParse(null).success;
    },
    apply(fn) {
      return fn(this);
    }
  });
  Object.defineProperty(inst, "description", {
    get() {
      return globalRegistry.get(inst)?.description;
    },
    configurable: true
  });
  return inst;
});
var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
  $ZodString.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params);
  const bag = inst._zod.bag;
  inst.format = bag.format ?? null;
  inst.minLength = bag.minimum ?? null;
  inst.maxLength = bag.maximum ?? null;
  _installLazyMethods(inst, "_ZodString", {
    regex(...args) {
      return this.check(_regex(...args));
    },
    includes(...args) {
      return this.check(_includes(...args));
    },
    startsWith(...args) {
      return this.check(_startsWith(...args));
    },
    endsWith(...args) {
      return this.check(_endsWith(...args));
    },
    min(...args) {
      return this.check(_minLength(...args));
    },
    max(...args) {
      return this.check(_maxLength(...args));
    },
    length(...args) {
      return this.check(_length(...args));
    },
    nonempty(...args) {
      return this.check(_minLength(1, ...args));
    },
    lowercase(params) {
      return this.check(_lowercase(params));
    },
    uppercase(params) {
      return this.check(_uppercase(params));
    },
    trim() {
      return this.check(_trim());
    },
    normalize(...args) {
      return this.check(_normalize(...args));
    },
    toLowerCase() {
      return this.check(_toLowerCase());
    },
    toUpperCase() {
      return this.check(_toUpperCase());
    },
    slugify() {
      return this.check(_slugify());
    }
  });
});
var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
  $ZodString.init(inst, def);
  _ZodString.init(inst, def);
  inst.email = (params) => inst.check(_email(ZodEmail, params));
  inst.url = (params) => inst.check(_url(ZodURL, params));
  inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
  inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
  inst.guid = (params) => inst.check(_guid(ZodGUID, params));
  inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
  inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
  inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
  inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
  inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
  inst.guid = (params) => inst.check(_guid(ZodGUID, params));
  inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
  inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
  inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
  inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
  inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
  inst.xid = (params) => inst.check(_xid(ZodXID, params));
  inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
  inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
  inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
  inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
  inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
  inst.e164 = (params) => inst.check(_e164(ZodE164, params));
  inst.datetime = (params) => inst.check(datetime2(params));
  inst.date = (params) => inst.check(date3(params));
  inst.time = (params) => inst.check(time2(params));
  inst.duration = (params) => inst.check(duration2(params));
});
function string2(params) {
  return _string(ZodString, params);
}
var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  _ZodString.init(inst, def);
});
var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
  $ZodEmail.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function email2(params) {
  return _email(ZodEmail, params);
}
var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
  $ZodGUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function guid2(params) {
  return _guid(ZodGUID, params);
}
var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
  $ZodUUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function uuid2(params) {
  return _uuid(ZodUUID, params);
}
function uuidv4(params) {
  return _uuidv4(ZodUUID, params);
}
function uuidv6(params) {
  return _uuidv6(ZodUUID, params);
}
function uuidv7(params) {
  return _uuidv7(ZodUUID, params);
}
var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
  $ZodURL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function url(params) {
  return _url(ZodURL, params);
}
function httpUrl(params) {
  return _url(ZodURL, {
    protocol: regexes_exports.httpProtocol,
    hostname: regexes_exports.domain,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
  $ZodEmoji.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function emoji2(params) {
  return _emoji2(ZodEmoji, params);
}
var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
  $ZodNanoID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function nanoid2(params) {
  return _nanoid(ZodNanoID, params);
}
var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
  $ZodCUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cuid3(params) {
  return _cuid(ZodCUID, params);
}
var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
  $ZodCUID2.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cuid22(params) {
  return _cuid2(ZodCUID2, params);
}
var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
  $ZodULID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ulid2(params) {
  return _ulid(ZodULID, params);
}
var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
  $ZodXID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function xid2(params) {
  return _xid(ZodXID, params);
}
var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
  $ZodKSUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ksuid2(params) {
  return _ksuid(ZodKSUID, params);
}
var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
  $ZodIPv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ipv42(params) {
  return _ipv4(ZodIPv4, params);
}
var ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => {
  $ZodMAC.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function mac2(params) {
  return _mac(ZodMAC, params);
}
var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
  $ZodIPv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ipv62(params) {
  return _ipv6(ZodIPv6, params);
}
var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
  $ZodCIDRv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cidrv42(params) {
  return _cidrv4(ZodCIDRv4, params);
}
var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
  $ZodCIDRv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cidrv62(params) {
  return _cidrv6(ZodCIDRv6, params);
}
var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
  $ZodBase64.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function base642(params) {
  return _base64(ZodBase64, params);
}
var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
  $ZodBase64URL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function base64url2(params) {
  return _base64url(ZodBase64URL, params);
}
var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
  $ZodE164.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function e1642(params) {
  return _e164(ZodE164, params);
}
var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
  $ZodJWT.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function jwt(params) {
  return _jwt(ZodJWT, params);
}
var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => {
  $ZodCustomStringFormat.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function stringFormat(format2, fnOrRegex, _params = {}) {
  return _stringFormat(ZodCustomStringFormat, format2, fnOrRegex, _params);
}
function hostname2(_params) {
  return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params);
}
function hex3(_params) {
  return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params);
}
function hash(alg, params) {
  const enc = params?.enc ?? "hex";
  const format2 = `${alg}_${enc}`;
  const regex = regexes_exports[format2];
  if (!regex)
    throw new Error(`Unrecognized hash format: ${format2}`);
  return _stringFormat(ZodCustomStringFormat, format2, regex, params);
}
var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
  $ZodNumber.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params);
  _installLazyMethods(inst, "ZodNumber", {
    gt(value, params) {
      return this.check(_gt(value, params));
    },
    gte(value, params) {
      return this.check(_gte(value, params));
    },
    min(value, params) {
      return this.check(_gte(value, params));
    },
    lt(value, params) {
      return this.check(_lt(value, params));
    },
    lte(value, params) {
      return this.check(_lte(value, params));
    },
    max(value, params) {
      return this.check(_lte(value, params));
    },
    int(params) {
      return this.check(int2(params));
    },
    safe(params) {
      return this.check(int2(params));
    },
    positive(params) {
      return this.check(_gt(0, params));
    },
    nonnegative(params) {
      return this.check(_gte(0, params));
    },
    negative(params) {
      return this.check(_lt(0, params));
    },
    nonpositive(params) {
      return this.check(_lte(0, params));
    },
    multipleOf(value, params) {
      return this.check(_multipleOf(value, params));
    },
    step(value, params) {
      return this.check(_multipleOf(value, params));
    },
    finite() {
      return this;
    }
  });
  const bag = inst._zod.bag;
  inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
  inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
  inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
  inst.isFinite = true;
  inst.format = bag.format ?? null;
});
function number6(params) {
  return _number(ZodNumber, params);
}
var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
  $ZodNumberFormat.init(inst, def);
  ZodNumber.init(inst, def);
});
function int2(params) {
  return _int(ZodNumberFormat, params);
}
function float32(params) {
  return _float32(ZodNumberFormat, params);
}
function float64(params) {
  return _float64(ZodNumberFormat, params);
}
function int32(params) {
  return _int32(ZodNumberFormat, params);
}
function uint32(params) {
  return _uint32(ZodNumberFormat, params);
}
var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
  $ZodBoolean.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params);
});
function boolean2(params) {
  return _boolean(ZodBoolean, params);
}
var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => {
  $ZodBigInt.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params);
  inst.gte = (value, params) => inst.check(_gte(value, params));
  inst.min = (value, params) => inst.check(_gte(value, params));
  inst.gt = (value, params) => inst.check(_gt(value, params));
  inst.gte = (value, params) => inst.check(_gte(value, params));
  inst.min = (value, params) => inst.check(_gte(value, params));
  inst.lt = (value, params) => inst.check(_lt(value, params));
  inst.lte = (value, params) => inst.check(_lte(value, params));
  inst.max = (value, params) => inst.check(_lte(value, params));
  inst.positive = (params) => inst.check(_gt(BigInt(0), params));
  inst.negative = (params) => inst.check(_lt(BigInt(0), params));
  inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params));
  inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params));
  inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
  const bag = inst._zod.bag;
  inst.minValue = bag.minimum ?? null;
  inst.maxValue = bag.maximum ?? null;
  inst.format = bag.format ?? null;
});
function bigint2(params) {
  return _bigint(ZodBigInt, params);
}
var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => {
  $ZodBigIntFormat.init(inst, def);
  ZodBigInt.init(inst, def);
});
function int64(params) {
  return _int64(ZodBigIntFormat, params);
}
function uint64(params) {
  return _uint64(ZodBigIntFormat, params);
}
var ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => {
  $ZodSymbol.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params);
});
function symbol(params) {
  return _symbol(ZodSymbol, params);
}
var ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => {
  $ZodUndefined.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params);
});
function _undefined3(params) {
  return _undefined2(ZodUndefined, params);
}
var ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
  $ZodNull.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params);
});
function _null3(params) {
  return _null2(ZodNull, params);
}
var ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => {
  $ZodAny.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params);
});
function any() {
  return _any(ZodAny);
}
var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
  $ZodUnknown.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params);
});
function unknown() {
  return _unknown(ZodUnknown);
}
var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
  $ZodNever.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params);
});
function never(params) {
  return _never(ZodNever, params);
}
var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => {
  $ZodVoid.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params);
});
function _void2(params) {
  return _void(ZodVoid, params);
}
var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => {
  $ZodDate.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params);
  inst.min = (value, params) => inst.check(_gte(value, params));
  inst.max = (value, params) => inst.check(_lte(value, params));
  const c = inst._zod.bag;
  inst.minDate = c.minimum ? new Date(c.minimum) : null;
  inst.maxDate = c.maximum ? new Date(c.maximum) : null;
});
function date4(params) {
  return _date(ZodDate, params);
}
var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
  $ZodArray.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params);
  inst.element = def.element;
  _installLazyMethods(inst, "ZodArray", {
    min(n2, params) {
      return this.check(_minLength(n2, params));
    },
    nonempty(params) {
      return this.check(_minLength(1, params));
    },
    max(n2, params) {
      return this.check(_maxLength(n2, params));
    },
    length(n2, params) {
      return this.check(_length(n2, params));
    },
    unwrap() {
      return this.element;
    }
  });
});
function array2(element, params) {
  return _array(ZodArray, element, params);
}
function keyof(schema) {
  const shape = schema._zod.def.shape;
  return _enum2(Object.keys(shape));
}
var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
  $ZodObjectJIT.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params);
  util_exports2.defineLazy(inst, "shape", () => {
    return def.shape;
  });
  _installLazyMethods(inst, "ZodObject", {
    keyof() {
      return _enum2(Object.keys(this._zod.def.shape));
    },
    catchall(catchall) {
      return this.clone({ ...this._zod.def, catchall });
    },
    passthrough() {
      return this.clone({ ...this._zod.def, catchall: unknown() });
    },
    loose() {
      return this.clone({ ...this._zod.def, catchall: unknown() });
    },
    strict() {
      return this.clone({ ...this._zod.def, catchall: never() });
    },
    strip() {
      return this.clone({ ...this._zod.def, catchall: void 0 });
    },
    extend(incoming) {
      return util_exports2.extend(this, incoming);
    },
    safeExtend(incoming) {
      return util_exports2.safeExtend(this, incoming);
    },
    merge(other) {
      return util_exports2.merge(this, other);
    },
    pick(mask) {
      return util_exports2.pick(this, mask);
    },
    omit(mask) {
      return util_exports2.omit(this, mask);
    },
    partial(...args) {
      return util_exports2.partial(ZodOptional, this, args[0]);
    },
    required(...args) {
      return util_exports2.required(ZodNonOptional, this, args[0]);
    }
  });
});
function object(shape, params) {
  const def = {
    type: "object",
    shape: shape ?? {},
    ...util_exports2.normalizeParams(params)
  };
  return new ZodObject(def);
}
function strictObject(shape, params) {
  return new ZodObject({
    type: "object",
    shape,
    catchall: never(),
    ...util_exports2.normalizeParams(params)
  });
}
function looseObject(shape, params) {
  return new ZodObject({
    type: "object",
    shape,
    catchall: unknown(),
    ...util_exports2.normalizeParams(params)
  });
}
var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
  $ZodUnion.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params);
  inst.options = def.options;
});
function union(options, params) {
  return new ZodUnion({
    type: "union",
    options,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => {
  ZodUnion.init(inst, def);
  $ZodXor.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params);
  inst.options = def.options;
});
function xor(options, params) {
  return new ZodXor({
    type: "union",
    options,
    inclusive: false,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
  ZodUnion.init(inst, def);
  $ZodDiscriminatedUnion.init(inst, def);
});
function discriminatedUnion(discriminator, options, params) {
  return new ZodDiscriminatedUnion({
    type: "union",
    options,
    discriminator,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
  $ZodIntersection.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params);
});
function intersection(left2, right2) {
  return new ZodIntersection({
    type: "intersection",
    left: left2,
    right: right2
  });
}
var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
  $ZodTuple.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params);
  inst.rest = (rest) => inst.clone({
    ...inst._zod.def,
    rest
  });
});
function tuple(items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new ZodTuple({
    type: "tuple",
    items,
    rest,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
  $ZodRecord.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
});
function record(keyType, valueType, params) {
  if (!valueType || !valueType._zod) {
    return new ZodRecord({
      type: "record",
      keyType: string2(),
      valueType: keyType,
      ...util_exports2.normalizeParams(valueType)
    });
  }
  return new ZodRecord({
    type: "record",
    keyType,
    valueType,
    ...util_exports2.normalizeParams(params)
  });
}
function partialRecord(keyType, valueType, params) {
  const k = clone2(keyType);
  k._zod.values = void 0;
  return new ZodRecord({
    type: "record",
    keyType: k,
    valueType,
    ...util_exports2.normalizeParams(params)
  });
}
function looseRecord(keyType, valueType, params) {
  return new ZodRecord({
    type: "record",
    keyType,
    valueType,
    mode: "loose",
    ...util_exports2.normalizeParams(params)
  });
}
var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => {
  $ZodMap.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
  inst.min = (...args) => inst.check(_minSize(...args));
  inst.nonempty = (params) => inst.check(_minSize(1, params));
  inst.max = (...args) => inst.check(_maxSize(...args));
  inst.size = (...args) => inst.check(_size(...args));
});
function map3(keyType, valueType, params) {
  return new ZodMap({
    type: "map",
    keyType,
    valueType,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => {
  $ZodSet.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params);
  inst.min = (...args) => inst.check(_minSize(...args));
  inst.nonempty = (params) => inst.check(_minSize(1, params));
  inst.max = (...args) => inst.check(_maxSize(...args));
  inst.size = (...args) => inst.check(_size(...args));
});
function set3(valueType, params) {
  return new ZodSet({
    type: "set",
    valueType,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
  $ZodEnum.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, params);
  inst.enum = def.entries;
  inst.options = Object.values(def.entries);
  const keys = new Set(Object.keys(def.entries));
  inst.extract = (values, params) => {
    const newEntries = {};
    for (const value of values) {
      if (keys.has(value)) {
        newEntries[value] = def.entries[value];
      } else
        throw new Error(`Key ${value} not found in enum`);
    }
    return new ZodEnum({
      ...def,
      checks: [],
      ...util_exports2.normalizeParams(params),
      entries: newEntries
    });
  };
  inst.exclude = (values, params) => {
    const newEntries = { ...def.entries };
    for (const value of values) {
      if (keys.has(value)) {
        delete newEntries[value];
      } else
        throw new Error(`Key ${value} not found in enum`);
    }
    return new ZodEnum({
      ...def,
      checks: [],
      ...util_exports2.normalizeParams(params),
      entries: newEntries
    });
  };
});
function _enum2(values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new ZodEnum({
    type: "enum",
    entries,
    ...util_exports2.normalizeParams(params)
  });
}
function nativeEnum(entries, params) {
  return new ZodEnum({
    type: "enum",
    entries,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
  $ZodLiteral.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, params);
  inst.values = new Set(def.values);
  Object.defineProperty(inst, "value", {
    get() {
      if (def.values.length > 1) {
        throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
      }
      return def.values[0];
    }
  });
});
function literal(value, params) {
  return new ZodLiteral({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...util_exports2.normalizeParams(params)
  });
}
var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => {
  $ZodFile.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params);
  inst.min = (size, params) => inst.check(_minSize(size, params));
  inst.max = (size, params) => inst.check(_maxSize(size, params));
  inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params));
});
function file(params) {
  return _file(ZodFile, params);
}
var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
  $ZodTransform.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params);
  inst._zod.parse = (payload, _ctx) => {
    if (_ctx.direction === "backward") {
      throw new $ZodEncodeError(inst.constructor.name);
    }
    payload.addIssue = (issue2) => {
      if (typeof issue2 === "string") {
        payload.issues.push(util_exports2.issue(issue2, payload.value, def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_issue.inst = inst);
        payload.issues.push(util_exports2.issue(_issue));
      }
    };
    const output = def.transform(payload.value, payload);
    if (output instanceof Promise) {
      return output.then((output2) => {
        payload.value = output2;
        payload.fallback = true;
        return payload;
      });
    }
    payload.value = output;
    payload.fallback = true;
    return payload;
  };
});
function transform(fn) {
  return new ZodTransform({
    type: "transform",
    transform: fn
  });
}
var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
  $ZodOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function optional(innerType) {
  return new ZodOptional({
    type: "optional",
    innerType
  });
}
var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => {
  $ZodExactOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function exactOptional(innerType) {
  return new ZodExactOptional({
    type: "optional",
    innerType
  });
}
var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
  $ZodNullable.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nullable(innerType) {
  return new ZodNullable({
    type: "nullable",
    innerType
  });
}
function nullish2(innerType) {
  return optional(nullable(innerType));
}
var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
  $ZodDefault.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeDefault = inst.unwrap;
});
function _default2(innerType, defaultValue) {
  return new ZodDefault({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : util_exports2.shallowClone(defaultValue);
    }
  });
}
var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
  $ZodPrefault.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function prefault(innerType, defaultValue) {
  return new ZodPrefault({
    type: "prefault",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : util_exports2.shallowClone(defaultValue);
    }
  });
}
var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
  $ZodNonOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nonoptional(innerType, params) {
  return new ZodNonOptional({
    type: "nonoptional",
    innerType,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => {
  $ZodSuccess.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function success(innerType) {
  return new ZodSuccess({
    type: "success",
    innerType
  });
}
var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
  $ZodCatch.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeCatch = inst.unwrap;
});
function _catch2(innerType, catchValue) {
  return new ZodCatch({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => {
  $ZodNaN.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params);
});
function nan(params) {
  return _nan(ZodNaN, params);
}
var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
  $ZodPipe.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params);
  inst.in = def.in;
  inst.out = def.out;
});
function pipe(in_, out) {
  return new ZodPipe({
    type: "pipe",
    in: in_,
    out
    // ...util.normalizeParams(params),
  });
}
var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => {
  ZodPipe.init(inst, def);
  $ZodCodec.init(inst, def);
});
function codec(in_, out, params) {
  return new ZodCodec({
    type: "pipe",
    in: in_,
    out,
    transform: params.decode,
    reverseTransform: params.encode
  });
}
function invertCodec(codec2) {
  const def = codec2._zod.def;
  return new ZodCodec({
    type: "pipe",
    in: def.out,
    out: def.in,
    transform: def.reverseTransform,
    reverseTransform: def.transform
  });
}
var ZodPreprocess = /* @__PURE__ */ $constructor("ZodPreprocess", (inst, def) => {
  ZodPipe.init(inst, def);
  $ZodPreprocess.init(inst, def);
});
var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
  $ZodReadonly.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function readonly(innerType) {
  return new ZodReadonly({
    type: "readonly",
    innerType
  });
}
var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => {
  $ZodTemplateLiteral.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params);
});
function templateLiteral(parts, params) {
  return new ZodTemplateLiteral({
    type: "template_literal",
    parts,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => {
  $ZodLazy.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.getter();
});
function lazy(getter) {
  return new ZodLazy({
    type: "lazy",
    getter
  });
}
var ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => {
  $ZodPromise.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function promise(innerType) {
  return new ZodPromise({
    type: "promise",
    innerType
  });
}
var ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => {
  $ZodFunction.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params);
});
function _function(params) {
  return new ZodFunction({
    type: "function",
    input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array2(unknown()),
    output: params?.output ?? unknown()
  });
}
var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
  $ZodCustom.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params);
});
function check(fn) {
  const ch = new $ZodCheck({
    check: "custom"
    // ...util.normalizeParams(params),
  });
  ch._zod.check = fn;
  return ch;
}
function custom(fn, _params) {
  return _custom(ZodCustom, fn ?? (() => true), _params);
}
function refine(fn, _params = {}) {
  return _refine(ZodCustom, fn, _params);
}
function superRefine(fn, params) {
  return _superRefine(fn, params);
}
var describe2 = describe;
var meta2 = meta;
function _instanceof(cls, params = {}) {
  const inst = new ZodCustom({
    type: "custom",
    check: "custom",
    fn: (data) => data instanceof cls,
    abort: true,
    ...util_exports2.normalizeParams(params)
  });
  inst._zod.bag.Class = cls;
  inst._zod.check = (payload) => {
    if (!(payload.value instanceof cls)) {
      payload.issues.push({
        code: "invalid_type",
        expected: cls.name,
        input: payload.value,
        inst,
        path: [...inst._zod.def.path ?? []]
      });
    }
  };
  return inst;
}
var stringbool = (...args) => _stringbool({
  Codec: ZodCodec,
  Boolean: ZodBoolean,
  String: ZodString
}, ...args);
function json(params) {
  const jsonSchema = lazy(() => {
    return union([string2(params), number6(), boolean2(), _null3(), array2(jsonSchema), record(string2(), jsonSchema)]);
  });
  return jsonSchema;
}
function preprocess(fn, schema) {
  return new ZodPreprocess({
    type: "pipe",
    in: transform(fn),
    out: schema
  });
}

// node_modules/zod/v4/classic/compat.js
var ZodIssueCode = {
  invalid_type: "invalid_type",
  too_big: "too_big",
  too_small: "too_small",
  invalid_format: "invalid_format",
  not_multiple_of: "not_multiple_of",
  unrecognized_keys: "unrecognized_keys",
  invalid_union: "invalid_union",
  invalid_key: "invalid_key",
  invalid_element: "invalid_element",
  invalid_value: "invalid_value",
  custom: "custom"
};
function setErrorMap(map4) {
  config({
    customError: map4
  });
}
function getErrorMap() {
  return config().customError;
}
var ZodFirstPartyTypeKind;
/* @__PURE__ */ (function(ZodFirstPartyTypeKind2) {
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));

// node_modules/zod/v4/classic/from-json-schema.js
var z = {
  ...schemas_exports2,
  ...checks_exports2,
  iso: iso_exports
};
var RECOGNIZED_KEYS = /* @__PURE__ */ new Set([
  // Schema identification
  "$schema",
  "$ref",
  "$defs",
  "definitions",
  // Core schema keywords
  "$id",
  "id",
  "$comment",
  "$anchor",
  "$vocabulary",
  "$dynamicRef",
  "$dynamicAnchor",
  // Type
  "type",
  "enum",
  "const",
  // Composition
  "anyOf",
  "oneOf",
  "allOf",
  "not",
  // Object
  "properties",
  "required",
  "additionalProperties",
  "patternProperties",
  "propertyNames",
  "minProperties",
  "maxProperties",
  // Array
  "items",
  "prefixItems",
  "additionalItems",
  "minItems",
  "maxItems",
  "uniqueItems",
  "contains",
  "minContains",
  "maxContains",
  // String
  "minLength",
  "maxLength",
  "pattern",
  "format",
  // Number
  "minimum",
  "maximum",
  "exclusiveMinimum",
  "exclusiveMaximum",
  "multipleOf",
  // Already handled metadata
  "description",
  "default",
  // Content
  "contentEncoding",
  "contentMediaType",
  "contentSchema",
  // Unsupported (error-throwing)
  "unevaluatedItems",
  "unevaluatedProperties",
  "if",
  "then",
  "else",
  "dependentSchemas",
  "dependentRequired",
  // OpenAPI
  "nullable",
  "readOnly"
]);
function detectVersion(schema, defaultTarget) {
  const $schema = schema.$schema;
  if ($schema === "https://json-schema.org/draft/2020-12/schema") {
    return "draft-2020-12";
  }
  if ($schema === "http://json-schema.org/draft-07/schema#") {
    return "draft-7";
  }
  if ($schema === "http://json-schema.org/draft-04/schema#") {
    return "draft-4";
  }
  return defaultTarget ?? "draft-2020-12";
}
function resolveRef(ref, ctx) {
  if (!ref.startsWith("#")) {
    throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
  }
  const path2 = ref.slice(1).split("/").filter(Boolean);
  if (path2.length === 0) {
    return ctx.rootSchema;
  }
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
  if (path2[0] === defsKey) {
    const key = path2[1];
    if (!key || !ctx.defs[key]) {
      throw new Error(`Reference not found: ${ref}`);
    }
    return ctx.defs[key];
  }
  throw new Error(`Reference not found: ${ref}`);
}
function convertBaseSchema(schema, ctx) {
  if (schema.not !== void 0) {
    if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
      return z.never();
    }
    throw new Error("not is not supported in Zod (except { not: {} } for never)");
  }
  if (schema.unevaluatedItems !== void 0) {
    throw new Error("unevaluatedItems is not supported");
  }
  if (schema.unevaluatedProperties !== void 0) {
    throw new Error("unevaluatedProperties is not supported");
  }
  if (schema.if !== void 0 || schema.then !== void 0 || schema.else !== void 0) {
    throw new Error("Conditional schemas (if/then/else) are not supported");
  }
  if (schema.dependentSchemas !== void 0 || schema.dependentRequired !== void 0) {
    throw new Error("dependentSchemas and dependentRequired are not supported");
  }
  if (schema.$ref) {
    const refPath = schema.$ref;
    if (ctx.refs.has(refPath)) {
      return ctx.refs.get(refPath);
    }
    if (ctx.processing.has(refPath)) {
      return z.lazy(() => {
        if (!ctx.refs.has(refPath)) {
          throw new Error(`Circular reference not resolved: ${refPath}`);
        }
        return ctx.refs.get(refPath);
      });
    }
    ctx.processing.add(refPath);
    const resolved = resolveRef(refPath, ctx);
    const zodSchema2 = convertSchema(resolved, ctx);
    ctx.refs.set(refPath, zodSchema2);
    ctx.processing.delete(refPath);
    return zodSchema2;
  }
  if (schema.enum !== void 0) {
    const enumValues = schema.enum;
    if (ctx.version === "openapi-3.0" && schema.nullable === true && enumValues.length === 1 && enumValues[0] === null) {
      return z.null();
    }
    if (enumValues.length === 0) {
      return z.never();
    }
    if (enumValues.length === 1) {
      return z.literal(enumValues[0]);
    }
    if (enumValues.every((v) => typeof v === "string")) {
      return z.enum(enumValues);
    }
    const literalSchemas = enumValues.map((v) => z.literal(v));
    if (literalSchemas.length < 2) {
      return literalSchemas[0];
    }
    return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
  }
  if (schema.const !== void 0) {
    return z.literal(schema.const);
  }
  const type = schema.type;
  if (Array.isArray(type)) {
    const typeSchemas = type.map((t) => {
      const typeSchema = { ...schema, type: t };
      return convertBaseSchema(typeSchema, ctx);
    });
    if (typeSchemas.length === 0) {
      return z.never();
    }
    if (typeSchemas.length === 1) {
      return typeSchemas[0];
    }
    return z.union(typeSchemas);
  }
  if (!type) {
    return z.any();
  }
  let zodSchema;
  switch (type) {
    case "string": {
      let stringSchema = z.string();
      if (schema.format) {
        const format2 = schema.format;
        if (format2 === "email") {
          stringSchema = stringSchema.check(z.email());
        } else if (format2 === "uri" || format2 === "uri-reference") {
          stringSchema = stringSchema.check(z.url());
        } else if (format2 === "uuid" || format2 === "guid") {
          stringSchema = stringSchema.check(z.uuid());
        } else if (format2 === "date-time") {
          stringSchema = stringSchema.check(z.iso.datetime());
        } else if (format2 === "date") {
          stringSchema = stringSchema.check(z.iso.date());
        } else if (format2 === "time") {
          stringSchema = stringSchema.check(z.iso.time());
        } else if (format2 === "duration") {
          stringSchema = stringSchema.check(z.iso.duration());
        } else if (format2 === "ipv4") {
          stringSchema = stringSchema.check(z.ipv4());
        } else if (format2 === "ipv6") {
          stringSchema = stringSchema.check(z.ipv6());
        } else if (format2 === "mac") {
          stringSchema = stringSchema.check(z.mac());
        } else if (format2 === "cidr") {
          stringSchema = stringSchema.check(z.cidrv4());
        } else if (format2 === "cidr-v6") {
          stringSchema = stringSchema.check(z.cidrv6());
        } else if (format2 === "base64") {
          stringSchema = stringSchema.check(z.base64());
        } else if (format2 === "base64url") {
          stringSchema = stringSchema.check(z.base64url());
        } else if (format2 === "e164") {
          stringSchema = stringSchema.check(z.e164());
        } else if (format2 === "jwt") {
          stringSchema = stringSchema.check(z.jwt());
        } else if (format2 === "emoji") {
          stringSchema = stringSchema.check(z.emoji());
        } else if (format2 === "nanoid") {
          stringSchema = stringSchema.check(z.nanoid());
        } else if (format2 === "cuid") {
          stringSchema = stringSchema.check(z.cuid());
        } else if (format2 === "cuid2") {
          stringSchema = stringSchema.check(z.cuid2());
        } else if (format2 === "ulid") {
          stringSchema = stringSchema.check(z.ulid());
        } else if (format2 === "xid") {
          stringSchema = stringSchema.check(z.xid());
        } else if (format2 === "ksuid") {
          stringSchema = stringSchema.check(z.ksuid());
        }
      }
      if (typeof schema.minLength === "number") {
        stringSchema = stringSchema.min(schema.minLength);
      }
      if (typeof schema.maxLength === "number") {
        stringSchema = stringSchema.max(schema.maxLength);
      }
      if (schema.pattern) {
        stringSchema = stringSchema.regex(new RegExp(schema.pattern));
      }
      zodSchema = stringSchema;
      break;
    }
    case "number":
    case "integer": {
      let numberSchema = type === "integer" ? z.number().int() : z.number();
      if (typeof schema.minimum === "number") {
        numberSchema = numberSchema.min(schema.minimum);
      }
      if (typeof schema.maximum === "number") {
        numberSchema = numberSchema.max(schema.maximum);
      }
      if (typeof schema.exclusiveMinimum === "number") {
        numberSchema = numberSchema.gt(schema.exclusiveMinimum);
      } else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") {
        numberSchema = numberSchema.gt(schema.minimum);
      }
      if (typeof schema.exclusiveMaximum === "number") {
        numberSchema = numberSchema.lt(schema.exclusiveMaximum);
      } else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") {
        numberSchema = numberSchema.lt(schema.maximum);
      }
      if (typeof schema.multipleOf === "number") {
        numberSchema = numberSchema.multipleOf(schema.multipleOf);
      }
      zodSchema = numberSchema;
      break;
    }
    case "boolean": {
      zodSchema = z.boolean();
      break;
    }
    case "null": {
      zodSchema = z.null();
      break;
    }
    case "object": {
      const shape = {};
      const properties = schema.properties || {};
      const requiredSet = new Set(schema.required || []);
      for (const [key, propSchema] of Object.entries(properties)) {
        const propZodSchema = convertSchema(propSchema, ctx);
        shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional();
      }
      if (schema.propertyNames) {
        const keySchema = convertSchema(schema.propertyNames, ctx);
        const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any();
        if (Object.keys(shape).length === 0) {
          zodSchema = z.record(keySchema, valueSchema);
          break;
        }
        const objectSchema2 = z.object(shape).passthrough();
        const recordSchema = z.looseRecord(keySchema, valueSchema);
        zodSchema = z.intersection(objectSchema2, recordSchema);
        break;
      }
      if (schema.patternProperties) {
        const patternProps = schema.patternProperties;
        const patternKeys = Object.keys(patternProps);
        const looseRecords = [];
        for (const pattern of patternKeys) {
          const patternValue = convertSchema(patternProps[pattern], ctx);
          const keySchema = z.string().regex(new RegExp(pattern));
          looseRecords.push(z.looseRecord(keySchema, patternValue));
        }
        const schemasToIntersect = [];
        if (Object.keys(shape).length > 0) {
          schemasToIntersect.push(z.object(shape).passthrough());
        }
        schemasToIntersect.push(...looseRecords);
        if (schemasToIntersect.length === 0) {
          zodSchema = z.object({}).passthrough();
        } else if (schemasToIntersect.length === 1) {
          zodSchema = schemasToIntersect[0];
        } else {
          let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
          for (let i = 2; i < schemasToIntersect.length; i++) {
            result = z.intersection(result, schemasToIntersect[i]);
          }
          zodSchema = result;
        }
        break;
      }
      const objectSchema = z.object(shape);
      if (schema.additionalProperties === false) {
        zodSchema = objectSchema.strict();
      } else if (typeof schema.additionalProperties === "object") {
        zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx));
      } else {
        zodSchema = objectSchema.passthrough();
      }
      break;
    }
    case "array": {
      const prefixItems = schema.prefixItems;
      const items = schema.items;
      if (prefixItems && Array.isArray(prefixItems)) {
        const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));
        const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0;
        if (rest) {
          zodSchema = z.tuple(tupleItems).rest(rest);
        } else {
          zodSchema = z.tuple(tupleItems);
        }
        if (typeof schema.minItems === "number") {
          zodSchema = zodSchema.check(z.minLength(schema.minItems));
        }
        if (typeof schema.maxItems === "number") {
          zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
        }
      } else if (Array.isArray(items)) {
        const tupleItems = items.map((item) => convertSchema(item, ctx));
        const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0;
        if (rest) {
          zodSchema = z.tuple(tupleItems).rest(rest);
        } else {
          zodSchema = z.tuple(tupleItems);
        }
        if (typeof schema.minItems === "number") {
          zodSchema = zodSchema.check(z.minLength(schema.minItems));
        }
        if (typeof schema.maxItems === "number") {
          zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
        }
      } else if (items !== void 0) {
        const element = convertSchema(items, ctx);
        let arraySchema = z.array(element);
        if (typeof schema.minItems === "number") {
          arraySchema = arraySchema.min(schema.minItems);
        }
        if (typeof schema.maxItems === "number") {
          arraySchema = arraySchema.max(schema.maxItems);
        }
        zodSchema = arraySchema;
      } else {
        zodSchema = z.array(z.any());
      }
      break;
    }
    default:
      throw new Error(`Unsupported type: ${type}`);
  }
  return zodSchema;
}
function convertSchema(schema, ctx) {
  if (typeof schema === "boolean") {
    return schema ? z.any() : z.never();
  }
  let baseSchema = convertBaseSchema(schema, ctx);
  const hasExplicitType = schema.type || schema.enum !== void 0 || schema.const !== void 0;
  if (schema.anyOf && Array.isArray(schema.anyOf)) {
    const options = schema.anyOf.map((s2) => convertSchema(s2, ctx));
    const anyOfUnion = z.union(options);
    baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
  }
  if (schema.oneOf && Array.isArray(schema.oneOf)) {
    const options = schema.oneOf.map((s2) => convertSchema(s2, ctx));
    const oneOfUnion = z.xor(options);
    baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
  }
  if (schema.allOf && Array.isArray(schema.allOf)) {
    if (schema.allOf.length === 0) {
      baseSchema = hasExplicitType ? baseSchema : z.any();
    } else {
      let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
      const startIdx = hasExplicitType ? 0 : 1;
      for (let i = startIdx; i < schema.allOf.length; i++) {
        result = z.intersection(result, convertSchema(schema.allOf[i], ctx));
      }
      baseSchema = result;
    }
  }
  if (schema.nullable === true && ctx.version === "openapi-3.0") {
    baseSchema = z.nullable(baseSchema);
  }
  if (schema.readOnly === true) {
    baseSchema = z.readonly(baseSchema);
  }
  if (schema.default !== void 0) {
    baseSchema = baseSchema.default(schema.default);
  }
  const extraMeta = {};
  const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
  for (const key of coreMetadataKeys) {
    if (key in schema) {
      extraMeta[key] = schema[key];
    }
  }
  const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
  for (const key of contentMetadataKeys) {
    if (key in schema) {
      extraMeta[key] = schema[key];
    }
  }
  for (const key of Object.keys(schema)) {
    if (!RECOGNIZED_KEYS.has(key)) {
      extraMeta[key] = schema[key];
    }
  }
  if (Object.keys(extraMeta).length > 0) {
    ctx.registry.add(baseSchema, extraMeta);
  }
  if (schema.description) {
    baseSchema = baseSchema.describe(schema.description);
  }
  return baseSchema;
}
function fromJSONSchema(schema, params) {
  if (typeof schema === "boolean") {
    return schema ? z.any() : z.never();
  }
  let normalized;
  try {
    normalized = JSON.parse(JSON.stringify(schema));
  } catch {
    throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
  }
  const version3 = detectVersion(normalized, params?.defaultTarget);
  const defs = normalized.$defs || normalized.definitions || {};
  const ctx = {
    version: version3,
    defs,
    refs: /* @__PURE__ */ new Map(),
    processing: /* @__PURE__ */ new Set(),
    rootSchema: normalized,
    registry: params?.registry ?? globalRegistry
  };
  return convertSchema(normalized, ctx);
}

// node_modules/zod/v4/classic/coerce.js
var coerce_exports = {};
__export(coerce_exports, {
  bigint: () => bigint3,
  boolean: () => boolean3,
  date: () => date5,
  number: () => number7,
  string: () => string3
});
function string3(params) {
  return _coercedString(ZodString, params);
}
function number7(params) {
  return _coercedNumber(ZodNumber, params);
}
function boolean3(params) {
  return _coercedBoolean(ZodBoolean, params);
}
function bigint3(params) {
  return _coercedBigint(ZodBigInt, params);
}
function date5(params) {
  return _coercedDate(ZodDate, params);
}

// node_modules/zod/v4/classic/external.js
config(en_default());

// src/nws.mts
function loadNWSPointInfo(lat, lon) {
  const fetchInit = defaultFetchInitObj();
  fetchInit["headers"] = {
    "accept": "application/geo+json"
  };
  const url2 = `https://api.weather.gov/points/${lat},${lon}`;
  return doFetchWithTimeout(url2, fetchInit).then((resp) => {
    if (resp.ok) {
      return resp.json();
    } else {
      throw new Error(`fetch ${url2} from NWS not ok: ${resp.status}`);
    }
  }).then((nwsJson) => {
    return NWSPointInfo.parse(nwsJson);
  });
}
function loadForecast(station) {
  return loadNWSPointInfo(station.latitude, station.longitude).then((pointInfo) => {
    const fetchInit = defaultFetchInitObj();
    fetchInit["headers"] = {
      "accept": "application/geo+json"
    };
    const url2 = pointInfo.properties.forecast;
    return doFetchWithTimeout(url2, fetchInit).then((resp) => {
      if (resp.ok) {
        return resp.json();
      } else {
        throw new Error(`fetch forecast for ${station.sourceId.toString()} not ok: ${resp.status}`);
      }
    }).then((rawJson) => {
      const nwsJson = NWSForecast.parse(rawJson);
      return nwsJson;
    });
  });
}
function nwsObservation(nws_station) {
  const fetchInit = defaultFetchInitObj();
  fetchInit["headers"] = {
    "accept": "application/geo+json"
  };
  const url2 = `https://api.weather.gov/stations/${nws_station}/observations/latest?require_qc=false`;
  return doFetchWithTimeout(url2, fetchInit).then((resp) => {
    if (resp.ok) {
      return resp.json();
    } else {
      throw new Error(`fetch observation ${nws_station} not ok: ${resp.status}`);
    }
  }).then((rawJson) => {
    const nwsJson = NWSObservation.parse(rawJson);
    return nwsJson;
  });
}
function loadObservation(station) {
  return loadNWSPointInfo(station.latitude, station.longitude).then((pointInfo) => {
    const fetchInit = defaultFetchInitObj();
    fetchInit["headers"] = {
      "accept": "application/geo+json"
    };
    const url2 = pointInfo.properties.observationStations;
    return doFetchWithTimeout(url2, fetchInit).then((resp) => {
      if (resp.ok) {
        return resp.json();
      } else {
        throw new Error(`fetch forecast fro ${station.sourceId.toString()} not ok: ${resp.status}`);
      }
    }).then((rawJson) => {
      const nwsJson = NWSObsStationCollection.parse(rawJson);
      return nwsJson;
    });
  }).then((obsSta) => {
    const nwsSta = obsSta.features[0].properties.stationIdentifier;
    return nwsObservation(nwsSta);
  });
}
var NWSBaseObj = object({
  "@context": tuple([string2(), object()]).optional()
});
var NWSPointInfo = NWSBaseObj.extend({
  id: string2(),
  type: literal("Feature"),
  geometry: object({
    type: literal("Point"),
    coordinates: array2(number6()).length(2)
  }),
  properties: object({
    cwa: string2(),
    gridId: string2(),
    gridX: number6(),
    gridY: number6(),
    forecast: string2(),
    forecastHourly: string2(),
    forecastGridData: string2(),
    observationStations: string2()
  })
});
var NWSForecastPeriod = object({
  number: number6(),
  name: string2(),
  startTime: iso_exports.datetime({ offset: true }),
  endTime: iso_exports.datetime({ offset: true }),
  shortForecast: string2(),
  detailedForecast: string2(),
  icon: url()
});
var NWSForecast = NWSBaseObj.extend({
  type: literal("Feature"),
  geometry: object({
    type: literal("Polygon"),
    coordinates: array2(array2(array2(number6()).length(2)))
  }),
  properties: object({
    generatedAt: iso_exports.datetime({ offset: true }),
    periods: array2(NWSForecastPeriod)
  })
});
var NWSObsMeasurement = object({
  unitCode: string2(),
  value: nullable(number6()),
  qualityControl: string2().optional()
});
var NWSObsStation = object({
  id: string2(),
  type: literal("Feature"),
  geometry: object({
    type: literal("Point"),
    coordinates: array2(number6()).length(2)
  }),
  properties: object({
    "@id": string2(),
    "@type": string2(),
    elevation: NWSObsMeasurement,
    stationIdentifier: string2(),
    name: string2(),
    timeZone: string2(),
    distance: NWSObsMeasurement,
    bearing: NWSObsMeasurement,
    forecast: string2(),
    county: string2(),
    fireWeatherZone: string2()
  })
});
var NWSObsStationCollection = NWSBaseObj.extend({
  type: literal("FeatureCollection"),
  features: array2(NWSObsStation),
  observationStations: array2(string2())
});
var NWSObservation = NWSBaseObj.extend({
  id: string2(),
  type: literal("Feature"),
  geometry: object({
    type: literal("Point"),
    coordinates: array2(number6()).length(2)
  }),
  properties: object({
    stationId: string2(),
    stationName: string2(),
    timestamp: iso_exports.datetime({ offset: true }),
    textDescription: string2(),
    temperature: NWSObsMeasurement.optional(),
    dewpoint: NWSObsMeasurement.optional(),
    windDirection: NWSObsMeasurement.optional(),
    windSpeed: NWSObsMeasurement.optional(),
    windGust: NWSObsMeasurement.optional(),
    barometricPressure: NWSObsMeasurement.optional(),
    seaLevelPressure: NWSObsMeasurement.optional(),
    visibility: NWSObsMeasurement.optional(),
    maxTemperatureLast24Hours: NWSObsMeasurement.optional(),
    minTemperatureLast24Hours: NWSObsMeasurement.optional(),
    precipitationLast3Hours: NWSObsMeasurement.optional(),
    relativeHumidity: NWSObsMeasurement.optional(),
    windChill: NWSObsMeasurement.optional(),
    cloudLayers: array2(object({
      base: NWSObsMeasurement.optional(),
      amount: string2()
    }))
  })
});

// src/ringserverweb.mts
var ringserverweb_exports = {};
__export(ringserverweb_exports, {
  DATALINK_PATH: () => DATALINK_PATH2,
  IRIS_HOST: () => IRIS_HOST3,
  NslcWithType: () => NslcWithType,
  RingserverConnection: () => RingserverConnection2,
  SEEDLINK_PATH: () => SEEDLINK_PATH2,
  StreamStat: () => StreamStat3,
  nslcSplit: () => nslcSplit,
  stationsFromStreams: () => stationsFromStreams2,
  typeForId: () => typeForId2
});

// src/ringserverweb4.mts
var ringserverweb4_exports = {};
__export(ringserverweb4_exports, {
  DATALINK_PATH: () => DATALINK_PATH,
  EARTHSCOPE_HOST: () => EARTHSCOPE_HOST2,
  IRIS_HOST: () => IRIS_HOST2,
  RingserverConnection: () => RingserverConnection,
  SEEDLINK_PATH: () => SEEDLINK_PATH,
  calcLatency: () => calcLatency,
  sidForId: () => sidForId,
  stationsFromStreams: () => stationsFromStreams,
  typeForId: () => typeForId
});
var SEEDLINK_PATH = "seedlink";
var DATALINK_PATH = "datalink";
var RingserverId = external_exports.object({
  software: external_exports.string(),
  organization: external_exports.string(),
  server_start: external_exports.string(),
  datalink_protocol: external_exports.array(external_exports.string()),
  seedlink_protocol: external_exports.array(external_exports.string())
});
var StreamStat2 = external_exports.object({
  id: external_exports.string(),
  start_time: external_exports.iso.datetime().transform(isoToDateTime),
  end_time: external_exports.iso.datetime().transform(isoToDateTime),
  earliest_packet_id: external_exports.number(),
  earliest_packet_time: external_exports.iso.datetime().transform(isoToDateTime),
  latest_packet_time: external_exports.iso.datetime().transform(isoToDateTime),
  latest_packet_id: external_exports.number(),
  data_latency: external_exports.number()
});
var StreamsResult = external_exports.object({
  software: external_exports.string(),
  organization: external_exports.string(),
  stream: external_exports.array(StreamStat2),
  accessTime: external_exports.custom((d) => d instanceof DateTime).optional()
});
var EARTHSCOPE_HOST2 = "rtserve.earthscope.org";
var IRIS_HOST2 = EARTHSCOPE_HOST2;
var RingserverConnection = class {
  constructor(host, port) {
    this.isFDSNSourceId = false;
    this.dlproto = "1.0";
    const hostStr = isNonEmptyStringArg(host) ? host : EARTHSCOPE_HOST2;
    if (hostStr.startsWith("http")) {
      const rs_url = new URL(hostStr);
      this._host = rs_url.hostname;
      this._port = parseInt(rs_url.port);
      this._protocol = rs_url.protocol;
      if (!Number.isInteger(this._port)) {
        this._port = 80;
      }
      this._prefix = rs_url.pathname;
    } else {
      this._protocol = "http:";
      this._host = hostStr;
      this._port = 80;
      this._prefix = "/";
    }
    if (this._host === EARTHSCOPE_HOST2) {
      this._protocol = "https:";
      this._port = 443;
    }
    if (isNumArg(port)) {
      this._port = port;
    }
    this._timeoutSec = 30;
  }
  /**
   * Gets/Sets the remote host to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  host(value) {
    doStringGetterSetter(this, "host", value);
    return this;
  }
  getHost() {
    return this._host;
  }
  /**
   * Gets/Sets the remote port to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  port(value) {
    doIntGetterSetter(this, "port", value);
    return this;
  }
  getPort() {
    return this._port;
  }
  /**
   * Gets/Sets the protocol, http or https. This should match the protocol
   *  of the page loaded, but is autocalculated and generally need not be set.
   *
   * @param value protocol, usually http or https
   * @returns the query when setting, the current value when no argument
   */
  protocol(value) {
    doStringGetterSetter(this, "protocol", value);
    return this;
  }
  getProtocol() {
    return this._protocol;
  }
  /**
   * Sets the prefix for the URL path.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  prefix(value) {
    if (value && !value.startsWith("/")) {
      value = "/" + value;
    }
    if (value && !value.endsWith("/")) {
      value = value + "/";
    }
    doStringGetterSetter(this, "prefix", value);
    return this;
  }
  getPrefix() {
    return this._prefix;
  }
  /**
   * Get/Set the timeout in seconds for the request. Default is 30.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  timeout(value) {
    doFloatGetterSetter(this, "timeoutSec", value);
    return this;
  }
  getTimeout() {
    return this._timeoutSec;
  }
  /*  .../id/json
  {
  "software":"ringserver/4.1.0-RC",
  "organization":"Test Ring Server 4",
  "server_start":"2025-05-14T00:33:11Z",
  "datalink_protocol":["DLPROTO:1.1"],
  "seedlink_protocol":["SLPROTO:4.0","SLPROTO:3.1"]
  }
   */
  /**
   * Pulls id result from ringserver /id parsed into an object with
   * 'ringserverVersion' and 'serverId' fields. Also sets the
   * isFDSNSourceId value as ringserver v4 uses new FDSN style ids
   * while
   *
   * @returns Result as a Promise.
   */
  pullId() {
    return pullJson(this.formIdURL(), this._timeoutSec).catch((_err) => {
      return pullText(appendToPath(this.formBaseURL(), "id"), this._timeoutSec).then((rawlines) => {
        const lines = rawlines.split("\n");
        let dlinfo = [`DLPROTO:1.0`];
        let slinfo = ["SLPROTO:3.1"];
        const version3 = lines[0];
        if (version3.startsWith("ringserver/4.0")) {
          this.isFDSNSourceId = true;
          dlinfo = [`DLPROTO:1.1`];
          slinfo = ["SLPROTO:3.1", "SLPROTO:4.0"];
        } else {
          this.isFDSNSourceId = false;
        }
        const organization = lines[1].substring("Organization: ".length);
        const serverStart = "";
        return {
          software: version3,
          organization,
          server_start: serverStart,
          datalink_protocol: dlinfo,
          seedlink_protocol: slinfo
        };
      });
    }).then((rawJson) => {
      return RingserverId.parse(rawJson);
    });
  }
  /**
   *  The optional matchPattern is a regular expression, so for example
   *  '.+_JSC_00_HH.' would get all HH? channels from any station name JSC.
   *
   * @param matchPattern regular expression to match
   * @returns Result as a Promise.
   */
  pullStreamIds(matchPattern) {
    let queryParams = "";
    if (matchPattern != null && matchPattern.length > 0) {
      queryParams = queryParams + "&match=" + matchPattern;
    }
    const url2 = this.formStreamIdsURL(queryParams);
    return pullText(url2, this._timeoutSec).then((raw) => {
      return raw.split("\n").filter((line) => line.length > 0);
    });
  }
  /*  .../streams/json
  {
    "software": "ringserver/4.1.0-RC",
    "organization": "Test Ring Server 4",
    "stream": [
      {
        "id": "FDSN:CO_BARN_00_H_N_E/MSEED",
        "start_time": "2025-05-20T22:20:58.425000Z",
        "end_time": "2025-05-21T19:09:14.015000Z",
        "earliest_packet_id": 191770832,
        "earliest_packet_time": "2025-05-20T22:21:01.423953Z",
        "latest_packet_time": "2025-05-21T19:09:15.537190Z",
        "latest_packet_id": 193469736,
        "data_latency": 2.159491
      },
   */
  /**
   * Pull streams, including start and end times, from the ringserver.
   * The optional matchPattern is a regular expression, so for example
   * '.+_JSC_00_HH.' would get all HH? channels from any station name JSC.
   * Result returned is an Promise.
   *
   * @param matchPattern regular expression to match
   * @returns promise to object with 'accessTime' as a DateTime
   * and 'streams' as an array of StreamStat objects.
   */
  pullStreams(matchPattern) {
    let queryParams = "";
    if (matchPattern && matchPattern.length > 0) {
      queryParams = "match=" + matchPattern;
    }
    const url2 = this.formStreamsURL(queryParams);
    return pullJson(url2, this._timeoutSec).then((raw) => {
      const accessTime = DateTime.utc();
      const out = StreamsResult.parse(raw);
      out.accessTime = accessTime;
      return out;
    });
  }
  getDataLinkURL() {
    let proto = "ws:";
    if (checkProtocol(this._protocol) === "https:") {
      proto = "wss:";
    }
    return proto + "//" + this._host + (this._port === 80 ? "" : ":" + this._port) + this._prefix + DATALINK_PATH;
  }
  getSeedLinkURL() {
    let proto = "ws:";
    if (checkProtocol(this._protocol) === "https:") {
      proto = "wss:";
    }
    return proto + "//" + this._host + (this._port === 80 ? "" : ":" + this._port) + this._prefix + SEEDLINK_PATH;
  }
  /**
   * Forms base url from protocol, host and port.
   *
   * @returns the string url
   */
  formBaseURL() {
    const protocol = protocolForKnownHost(this._host, this._protocol);
    let colon = ":";
    if (protocol.endsWith(colon)) {
      colon = "";
    }
    let port;
    if (this._port === 0) {
      port = defaultPortStringForProtocol(protocol, 80);
    } else {
      port = defaultPortStringForProtocol(protocol, this._port);
    }
    return `${checkProtocol(protocol)}${colon}//${this._host}${port}${this._prefix}`;
  }
  /**
   * Forms the ringserver id/json url.
   *
   * @returns the id url
   */
  formIdURL() {
    return appendToPath(this.formBaseURL(), "id/json");
  }
  /**
   * Forms the ringserver streams/json url using the query parameters.
   *
   * @param queryParams optional string of query parameters
   * @returns the streams url
   */
  formStreamsURL(queryParams) {
    return appendToPath(this.formBaseURL(), "streams/json") + (isNonEmptyStringArg(queryParams) && queryParams.length > 0 ? "?" + queryParams : "");
  }
  /**
   * Forms the ringserver stream ids url using the query parameters.
   *
   * @param queryParams optional string of query parameters
   * @returns the stream ids url
   */
  formStreamIdsURL(queryParams) {
    let qpStr = "";
    if (queryParams != null && queryParams.length > 0) {
      if (queryParams.startsWith("&")) {
        queryParams = queryParams.substring(1);
      }
      qpStr = `?${queryParams}`;
    }
    const path2 = appendToPath(this.formBaseURL(), "streamids");
    const out = `${path2}${qpStr}`;
    return out;
  }
};
function stationsFromStreams(streams) {
  const out = /* @__PURE__ */ new Map();
  for (const s2 of streams) {
    const sid = sidForId(s2.id);
    if (sid == null || sid instanceof NetworkSourceId) {
      continue;
    }
    const staSid = sid instanceof StationSourceId ? sid : sid.stationSourceId();
    const staKey = staSid.networkCode + "_" + staSid.stationCode;
    let stat = out.get(staKey);
    if (!isDef(stat)) {
      stat = StreamStat2.parse({
        id: staKey,
        start_time: s2.start_time,
        end_time: s2.end_time,
        earliest_packet_id: s2.earliest_packet_id,
        earliest_packet_time: s2.earliest_packet_time,
        latest_packet_time: s2.latest_packet_time,
        latest_packet_id: s2.latest_packet_id,
        data_latency: s2.data_latency
      });
      out.set(staKey, stat);
    } else {
      if (stat.start_time > s2.start_time) {
        stat.start_time = s2.start_time;
      }
      if (stat.end_time < s2.end_time) {
        stat.end_time = s2.end_time;
      }
    }
  }
  return Array.from(out.values());
}
function calcLatency(stat) {
  return Interval.fromDateTimes(stat.end_time, DateTime.utc()).toDuration();
}
function typeForId(id2) {
  const split = id2.split("/");
  if (split.length >= 2) {
    return split[split.length - 1];
  }
  return null;
}
function sidForId(id2) {
  const split = id2.split("/");
  if (split.length >= 1) {
    const sidStr = split[0];
    if (sidStr.startsWith(FDSN_PREFIX)) {
      return parseSourceId(split[0]);
    } else {
      const items = split[0].split("_");
      if (items.length === 4) {
        const nslc = NslcId.parse(split[0], "_");
        return FDSNSourceId.fromNslcId(nslc);
      }
    }
  }
  return null;
}

// src/ringserverweb.mts
var SEEDLINK_PATH2 = "seedlink";
var DATALINK_PATH2 = "datalink";
var IRIS_HOST3 = "rtserve.iris.washington.edu";
var ORG = "Organization: ";
var RingserverConnection2 = class {
  constructor(host, port) {
    this.isFDSNSourceId = false;
    this.dlproto = "1.0";
    const hostStr = isNonEmptyStringArg(host) ? host : IRIS_HOST3;
    if (hostStr.startsWith("http")) {
      const rs_url = new URL(hostStr);
      this._host = rs_url.hostname;
      this._port = parseInt(rs_url.port);
      this._protocol = rs_url.protocol;
      if (!Number.isInteger(this._port)) {
        this._port = 80;
      }
      this._prefix = rs_url.pathname;
    } else {
      this._protocol = "http:";
      this._host = hostStr;
      this._port = 80;
      this._prefix = "/";
    }
    if (isNumArg(port)) {
      this._port = port;
    }
    this._timeoutSec = 30;
  }
  /**
   * Gets/Sets the remote host to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  host(value) {
    doStringGetterSetter(this, "host", value);
    return this;
  }
  getHost() {
    return this._host;
  }
  /**
   * Gets/Sets the remote port to connect to.
   *
   * @param value  new value to set
   * @returns this
   */
  port(value) {
    doIntGetterSetter(this, "port", value);
    return this;
  }
  getPort() {
    return this._port;
  }
  /**
   * Sets the prefix for the URL path.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  prefix(value) {
    if (value && !value.startsWith("/")) {
      value = "/" + value;
    }
    doStringGetterSetter(this, "prefix", value);
    return this;
  }
  getPrefix() {
    return this._prefix;
  }
  /**
   * Get/Set the timeout in seconds for the request. Default is 30.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  timeout(value) {
    doFloatGetterSetter(this, "timeoutSec", value);
    return this;
  }
  getTimeout() {
    return this._timeoutSec;
  }
  /**
   * Pulls id result from ringserver /id parsed into an object with
   * 'ringserverVersion' and 'serverId' fields. Also sets the
   * isFDSNSourceId value as ringserver v4 uses new FDSN style ids
   * while
   *
   * @returns Result as a Promise.
   */
  pullId() {
    return pullText(this.formIdURL(), this._timeoutSec).then((raw) => {
      const lines = raw.split("\n");
      const ringserver_v4 = "ringserver/4";
      const version3 = lines[0];
      let organization = lines[1];
      if (organization.startsWith(ORG)) {
        organization = organization.substring(ORG.length);
      }
      if (version3.startsWith(ringserver_v4)) {
        this.isFDSNSourceId = true;
      }
      this.dlproto = extractDLProto(lines);
      if (this.dlproto === "1.0") {
        if (version3.startsWith(ringserver_v4)) {
          this.isFDSNSourceId = true;
        } else {
          this.isFDSNSourceId = false;
        }
      } else {
        this.isFDSNSourceId = true;
      }
      return {
        ringserverVersion: lines[0],
        serverId: organization,
        datalink: "DLPROTO:1.0",
        seedlink: "SLPROTO:3.1"
      };
    });
  }
  /**
   *  Use numeric level (1-6) to pull just IDs from ringserver.
   *  In a default ringserver,
   *  level=1 would return all networks like
   *  CO
   *  and level=2 would return all stations like
   *  CO_JSC
   *  If level is falsy/missing, level=6 is used.
   *  The optional matchPattern is a regular expression, so for example
   *  '.+_JSC_00_HH.' would get all HH? channels from any station name JSC.
   *
   * @param level 1-6
   * @param matchPattern regular expression to match
   * @returns Result as a Promise.
   */
  pullStreamIds(level, matchPattern) {
    let queryParams = "level=6";
    if (isNumArg(level) && level > 0) {
      queryParams = "level=" + level;
    }
    if (matchPattern && matchPattern.length > 0) {
      queryParams = queryParams + "&match=" + matchPattern;
    }
    const url2 = this.formStreamIdsURL(queryParams);
    return pullText(url2, this._timeoutSec).then((raw) => {
      return raw.split("\n").filter((line) => line.length > 0);
    });
  }
  /**
   * Pull streams, including start and end times, from the ringserver.
   * The optional matchPattern is a regular expression, so for example
   * '.+_JSC_00_HH.' would get all HH? channels from any station name JSC.
   * Result returned is an Promise.
   *
   * @param matchPattern regular expression to match
   * @returns promise to object with 'accessTime' as a DateTime
   * and 'streams' as an array of StreamStat objects.
   */
  pullStreams(matchPattern) {
    let queryParams = "";
    if (matchPattern && matchPattern.length > 0) {
      queryParams = "match=" + matchPattern;
    }
    const url2 = this.formStreamsURL(queryParams);
    return pullText(url2, this._timeoutSec).then((raw) => {
      const lines = raw.split("\n");
      const out = {
        accessTime: DateTime.utc(),
        streams: []
      };
      for (const line of lines) {
        if (line.length === 0) {
          continue;
        }
        const vals = line.split(/\s+/);
        if (vals.length === 0) {
          continue;
        } else if (vals.length >= 2) {
          out.streams.push(new StreamStat3(vals[0], vals[1], vals[2]));
        } else {
          log("Bad /streams line, skipping: '" + line + "'");
        }
      }
      return out;
    });
  }
  getDataLinkURL() {
    let proto = "ws:";
    if (checkProtocol(this._protocol) === "https:") {
      proto = "wss:";
    }
    return proto + "//" + this._host + (this._port === 80 ? "" : ":" + this._port) + this._prefix + DATALINK_PATH2;
  }
  getSeedLinkURL() {
    let proto = "ws:";
    if (checkProtocol(this._protocol) === "https:") {
      proto = "wss:";
    }
    return proto + "//" + this._host + (this._port === 80 ? "" : ":" + this._port) + this._prefix + SEEDLINK_PATH2;
  }
  /**
   * Forms base url from protocol, host and port.
   *
   * @returns the string url
   */
  formBaseURL() {
    if (this._port === 0) {
      this._port = 80;
    }
    const port = defaultPortStringForProtocol(this._protocol, this._port);
    return `${checkProtocol(this._protocol)}//${this._host}${port}${this._prefix}`;
  }
  /**
   * Forms the ringserver id url.
   *
   * @returns the id url
   */
  formIdURL() {
    return appendToPath(this.formBaseURL(), "id");
  }
  /**
   * Forms the ringserver streams url using the query parameters.
   *
   * @param queryParams optional string of query parameters
   * @returns the streams url
   */
  formStreamsURL(queryParams) {
    return appendToPath(this.formBaseURL(), "streams") + (isNonEmptyStringArg(queryParams) && queryParams.length > 0 ? "?" + queryParams : "");
  }
  /**
   * Forms the ringserver stream ids url using the query parameters.
   *
   * @param queryParams optional string of query parameters
   * @returns the stream ids url
   */
  formStreamIdsURL(queryParams) {
    return appendToPath(this.formBaseURL(), "streamids") + (queryParams && queryParams.length > 0 ? "?" + queryParams : "");
  }
};
function stationsFromStreams2(streams) {
  const out = /* @__PURE__ */ new Map();
  for (const s2 of streams) {
    const sid = sidForId(s2.key);
    if (sid == null || sid instanceof NetworkSourceId) {
      continue;
    }
    const staSid = sid instanceof StationSourceId ? sid : sid.stationSourceId();
    const staKey = staSid.networkCode + "_" + staSid.stationCode;
    let stat = out.get(staKey);
    if (!isDef(stat)) {
      stat = new StreamStat3(staKey, s2.startRaw, s2.endRaw);
      out.set(staKey, stat);
    } else {
      if (stat.start > s2.start) {
        stat.start = s2.start;
        stat.startRaw = s2.startRaw;
      }
      if (stat.end < s2.end) {
        stat.end = s2.end;
        stat.endRaw = s2.endRaw;
      }
    }
  }
  return Array.from(out.values());
}
var NslcWithType = class {
  constructor(type, nslc) {
    this.type = type;
    this.nslc = nslc;
  }
};
function typeForId2(id2) {
  const split = id2.split("/");
  if (split.length >= 2) {
    return split[split.length - 1];
  }
  return null;
}
function nslcSplit(id2) {
  const split = id2.split("/");
  if (split[0].startsWith(FDSN_PREFIX)) {
    const sid = parseSourceId(split[0]);
    if (sid instanceof FDSNSourceId) {
      return new NslcWithType(
        split[1],
        sid.asNslc()
      );
    } else {
      throw new Error("tried to split, not an FDSN SourceId: " + id2);
    }
  }
  const nslc = split[0].split("_");
  if (nslc.length === 4) {
    return new NslcWithType(
      split[1],
      new NslcId(nslc[0], nslc[1], nslc[2], nslc[3])
    );
  } else {
    throw new Error("tried to split, did not find 4 elements in array: " + id2);
  }
}
var StreamStat3 = class {
  constructor(key, start2, end) {
    this.key = key;
    this.startRaw = start2;
    this.endRaw = end;
    if (this.startRaw.indexOf(".") !== -1 && this.startRaw.indexOf(".") < this.startRaw.length - 4) {
      this.startRaw = this.startRaw.substring(
        0,
        this.startRaw.indexOf(".") + 4
      );
    }
    if (this.startRaw.charAt(this.startRaw.length - 1) !== "Z") {
      this.startRaw = this.startRaw + "Z";
    }
    if (this.endRaw.indexOf(".") !== -1 && this.endRaw.indexOf(".") < this.endRaw.length - 4) {
      this.endRaw = this.endRaw.substring(0, this.endRaw.indexOf(".") + 4);
    }
    if (this.endRaw.charAt(this.endRaw.length - 1) !== "Z") {
      this.endRaw = this.endRaw + "Z";
    }
    this.start = isoToDateTime(this.startRaw);
    this.end = isoToDateTime(this.endRaw);
    this.startRaw = start2;
    this.endRaw = end;
  }
  /**
   * Calculates latency time difference between last packet and current time.
   *
   * @param accessTime time latency is calculated relative to
   * @returns latency
   */
  calcLatency(accessTime) {
    if (!accessTime) accessTime = DateTime.utc();
    return this.end.diff(accessTime);
  }
};

// src/sacpolezero.mts
var sacpolezero_exports = {};
__export(sacpolezero_exports, {
  SacPoleZero: () => SacPoleZero,
  geomspace: () => geomspace,
  linspace: () => linspace,
  logspace: () => logspace
});
var SacPoleZero = class _SacPoleZero {
  constructor(poles, zeros, constant) {
    this.poles = poles;
    this.zeros = zeros;
    this.constant = constant;
    this.mulFactor = 1;
    this.sd = 1;
    this.A0 = 1;
  }
  toString() {
    const s2 = ["sacPoleZero:"];
    s2.push("ZEROS " + this.zeros.length);
    for (let i = 0; i < this.zeros.length; i++) {
      s2.push("    " + this.zeros[i].real() + " " + this.zeros[i].imag());
    }
    s2.push("POLES " + this.poles.length);
    for (let i = 0; i < this.poles.length; i++) {
      s2.push("    " + this.poles[i].real() + " " + this.poles[i].imag());
    }
    s2.push("CONSTANT " + this.constant);
    if (isNumArg(this.gamma) && isNumArg(this.mulFactor) && isNumArg(this.sd) && isNumArg(this.A0)) {
      s2.push("*    gamma: " + this.gamma);
      s2.push("*    mulFactor: " + this.mulFactor);
      s2.push("*    sd: " + this.sd);
      s2.push("*    A0: " + this.A0);
    }
    return s2.join("\n");
  }
  evalPoleZeroInverse(freq) {
    const s2 = new Complex(0, 2 * Math.PI * freq);
    let zeroOut = new Complex(1, 0);
    let poleOut = new Complex(1, 0);
    for (let i = 0; i < this.poles.length; i++) {
      poleOut = poleOut.timesComplex(s2.minusComplex(this.poles[i]));
    }
    for (let i = 0; i < this.zeros.length; i++) {
      if (s2.real() === this.zeros[i].real() && s2.imag() === this.zeros[i].imag()) {
        return new Complex(0, 0);
      }
      zeroOut = zeroOut.timesComplex(s2.minusComplex(this.zeros[i]));
    }
    const out = poleOut.overComplex(zeroOut);
    return out.overReal(this.constant);
  }
  trimZeros(gamma2) {
    for (let i = 0; i < gamma2; i++) {
      const z2 = this.zeros[this.zeros.length - 1 - i];
      if (z2.real() !== 0 || z2.imag() !== 0) {
        throw new Error(
          `Attempt to trim ${gamma2} zeros from SacPoleZero, but zero isn't 0+i0: ${stringify(z2)}`
        );
      }
    }
    let trimmedZeros = this.zeros.slice().reverse();
    for (let i = 0; i < gamma2; i++) {
      const idx = trimmedZeros.findIndex(
        (d) => d.real() === 0 && d.imag() === 0
      );
      trimmedZeros.splice(idx, 1);
    }
    trimmedZeros = trimmedZeros.reverse();
    this.zeros = trimmedZeros;
  }
  toText() {
    const s2 = [];
    s2.push("ZEROS " + this.zeros.length);
    for (let i = 0; i < this.zeros.length; i++) {
      s2.push("    " + this.zeros[i].real() + " " + this.zeros[i].imag());
    }
    s2.push("POLES " + this.poles.length);
    for (let i = 0; i < this.poles.length; i++) {
      s2.push("    " + this.poles[i].real() + " " + this.poles[i].imag());
    }
    s2.push("CONSTANT " + this.constant);
    return s2.join("\n");
  }
  /**
   * Caclulates the frequency response from the given poles and zeros.
   *
   * @param freqs frequencies to compute
   * @returns  frequency response
   */
  calcForDisplay(freqs) {
    const out = freqs.map((freq) => {
      let respAtS = this.evalPoleZeroInverse(freq);
      respAtS = new Complex(1, 0).overComplex(respAtS);
      return respAtS;
    });
    return out;
  }
  /**
   * Parses a string in sac polezero format into a SacPoleZero.
   *
   * @param data string to parse
   * @returns SacPoleZero instance
   */
  static parse(data) {
    const pz = {
      zeros: Array(0),
      poles: Array(0),
      constant: 1
    };
    const lines = data.split("\n");
    let numZeros;
    let numPoles;
    let i = 0;
    while (i < lines.length) {
      let l2 = lines[i];
      let items = l2.trim().split(/ +/);
      if (items[0] === "ZEROS") {
        numZeros = parseInt(items[1]);
        i++;
        l2 = lines[i];
        items = l2.trim().split(/ +/);
        while (i < lines.length && pz.zeros.length < numZeros) {
          if (items[0] === "POLES") {
            for (let z2 = pz.zeros.length; z2 < numZeros; z2++) {
              pz.zeros.push(new Complex(0, 0));
            }
            break;
          } else {
            const real = parseFloat(items[0]);
            const imag = parseFloat(items[1]);
            pz.zeros.push(new Complex(real, imag));
          }
          i++;
          l2 = lines[i];
          items = l2.trim().split(/ +/);
        }
      }
      if (items[0] === "POLES") {
        numPoles = parseInt(items[1]);
        i++;
        l2 = lines[i];
        items = l2.trim().split(/ +/);
        while (i < lines.length && pz.poles.length < numPoles) {
          if (items[0] === "CONSTANT") {
            for (let z2 = pz.poles.length; z2 < numPoles; z2++) {
              pz.poles.push(new Complex(0, 0));
            }
            break;
          } else {
            const real = parseFloat(items[0]);
            const imag = parseFloat(items[1]);
            pz.poles.push(new Complex(real, imag));
          }
          i++;
          l2 = lines[i];
          items = l2.trim().split(/ +/);
        }
      }
      if (items[0] === "CONSTANT") {
        pz.constant = parseFloat(items[1]);
      }
      i++;
    }
    return new _SacPoleZero(pz.poles, pz.zeros, pz.constant);
  }
};
function geomspace(start2, stop, num) {
  const log_start = Math.log(start2);
  const log_stop = Math.log(stop);
  return logspace(log_start, log_stop, num);
}
function logspace(start2, stop, num) {
  return linspace(start2, stop, num).map((n2) => Math.pow(10, n2));
}
function linspace(start2, stop, num) {
  const delta = (stop - start2) / (num - 1);
  const out = [];
  for (let i = 0; i < num; i++) {
    out.push(start2 + i * delta);
  }
  return out;
}

// src/seedlink.mts
var seedlink_exports = {};
__export(seedlink_exports, {
  SeedlinkConnection: () => SeedlinkConnection2,
  WS_SEEDLINK3_SUBPROTOCOL: () => WS_SEEDLINK3_SUBPROTOCOL
});
var WS_SEEDLINK3_SUBPROTOCOL = "SeedLink3.1";
var SeedlinkConnection2 = class {
  constructor(url2, requestConfig, receiveMiniseedFn, errorHandler) {
    this.helloLines = [];
    this.url = url2;
    this.requestConfig = requestConfig;
    this.receiveMiniseedFn = receiveMiniseedFn;
    this.errorHandler = errorHandler;
    this.logCommandFn = (msg) => {
    };
    this.closeFn = null;
    this.command = "DATA";
    this.webSocket = null;
    this.subprotocol = WS_SEEDLINK3_SUBPROTOCOL;
  }
  setTimeCommand(startTime) {
    this.command = "TIME " + startTime.toFormat("yyyy,LL,dd,HH,mm,ss");
  }
  setOnError(errorHandler) {
    this.errorHandler = errorHandler;
  }
  setOnClose(closeFn) {
    this.closeFn = closeFn;
  }
  connect() {
    return this.interactiveConnect().then(() => {
      return this.sendHello();
    }).then((lines) => {
      this.helloLines = lines;
      return this.sendCmdArray(this.requestConfig);
    }).then(() => {
      return this.sendCmdArray([this.command]);
    }).then((val) => {
      if (this.webSocket === null) {
        throw new Error("websocket is null");
      }
      this.webSocket.onmessage = (event) => {
        this.handle(event);
      };
      const cmd = "END\r";
      if (this.logCommandFn) {
        this.logCommandFn(cmd);
      }
      this.webSocket.send(cmd);
      return val;
    }).catch((err) => {
      this.close();
      const insureErr = err instanceof Error ? err : new Error(stringify(err));
      if (this.errorHandler) {
        this.errorHandler(insureErr);
      } else {
        throw insureErr;
      }
    });
  }
  interactiveConnect() {
    if (this.webSocket) {
      this.webSocket.close();
      this.webSocket = null;
    }
    return new Promise((resolve, reject) => {
      try {
        const webSocket = new WebSocket(this.url, this.subprotocol);
        this.webSocket = webSocket;
        webSocket.binaryType = "arraybuffer";
        webSocket.onopen = () => {
          resolve(this);
        };
        webSocket.onerror = (event) => {
          const evtError = toError(event);
          this.handleError(evtError);
          reject(evtError);
        };
        webSocket.onclose = (closeEvent) => {
          if (this.closeFn) {
            this.closeFn(closeEvent);
          }
          if (this.webSocket) {
            this.webSocket = null;
          }
        };
      } catch (err) {
        this.close();
        const evtError = toError(err);
        if (this.errorHandler) {
          this.errorHandler(evtError);
        }
        reject(evtError);
      }
    }).then(function(sl3) {
      return sl3;
    }).catch((e) => {
      if (!this.webSocket?.protocol || this.webSocket.protocol.length === 0) {
        throw new Error(`fail to create websocket, possible due to subprotocol: sent subprotocol=${this.subprotocol} received empty`);
      }
      throw e;
    });
  }
  close() {
    if (this.webSocket) {
      this.webSocket.close();
      this.webSocket = null;
    }
  }
  handle(event) {
    if (event.data instanceof ArrayBuffer || event.data instanceof SharedArrayBuffer) {
      const data = event.data;
      if (data.byteLength < 64) {
      } else {
        this.handleMiniseed(data);
      }
    } else {
      this.handleError(new Error("Unknown message type" + JSON.stringify(event)));
    }
  }
  handleMiniseed(data) {
    try {
      if (data.byteLength < 64) {
        this.errorHandler(
          new Error(
            "message too small to be miniseed: " + data.byteLength + " " + dataViewToString(new DataView(data))
          )
        );
        return;
      }
      const slHeader = new DataView(data, 0, 8);
      if (slHeader.getInt8(0) === 83 && slHeader.getInt8(1) === 76) {
        let seqStr = "";
        for (let i = 0; i < 6; i++) {
          seqStr = seqStr + String.fromCharCode(slHeader.getInt8(2 + i));
        }
        const dataView = new DataView(data, 8, data.byteLength - 8);
        const out = {
          rawsequence: seqStr,
          sequence: parseInt(seqStr, 16),
          miniseed: parseSingleDataRecord(dataView)
        };
        this.receiveMiniseedFn(out);
      } else {
        throw new Error(
          "Not a seedlink packet, no starting SL: " + slHeader.getInt8(0) + " " + slHeader.getInt8(1)
        );
      }
    } catch (e) {
      this.errorHandler(toError(e));
      this.close();
    }
  }
  isConnected() {
    return this.webSocket !== null;
  }
  /**
   * Sends initial HELLO to server and waits for response.
   *
   * @returns            Promise that resolves to the response from the server.
   */
  sendHello() {
    const mythis = this;
    const webSocket = this.webSocket;
    const promise2 = new Promise(function(resolve, reject) {
      if (webSocket) {
        webSocket.onmessage = function(event) {
          if (event.data instanceof ArrayBuffer || event.data instanceof SharedArrayBuffer) {
            const data = event.data;
            const replyMsg = dataViewToString(new DataView(data));
            if (mythis.logCommandFn) {
              mythis.logCommandFn(replyMsg);
            }
            const lines = replyMsg.trim().split("\r");
            if (lines.length === 2) {
              resolve([lines[0], lines[1]]);
            } else {
              reject(new Error("not 2 lines: " + replyMsg));
            }
          } else {
            reject(new Error("event.data not ArrayBufferLike?"));
          }
        };
        const cmd = "HELLO\r";
        if (mythis.logCommandFn) {
          mythis.logCommandFn(cmd);
        }
        webSocket.send(cmd);
      } else {
        reject(new Error("webSocket has been closed"));
      }
    });
    return promise2;
  }
  /**
   * Sends an array of commands, each as a Promise waiting for the 'OK' response
   * before sending the next.
   *
   * @param   cmd array of commands to send
   * @returns      Promise that resolves to the 'OK' returned by the last
   *   command if successful, or rejects on the first failure.
   */
  sendCmdArray(cmd) {
    return cmd.reduce((accum, next) => {
      return accum.then(() => {
        return this.createCmdPromise(next);
      });
    }, Promise.resolve("OK"));
  }
  /**
   * creates a Promise that sends a command and waits resolved with the result.
   *
   * @param   mycmd command string to send.
   * @returns        Promise that resolves to the reply from the server.
   */
  createCmdPromise(mycmd) {
    const mythis = this;
    const webSocket = this.webSocket;
    const promise2 = new Promise(function(resolve, reject) {
      if (webSocket) {
        webSocket.onmessage = function(event) {
          if (event.data instanceof ArrayBuffer || event.data instanceof SharedArrayBuffer) {
            const data = event.data;
            const replyMsg = dataViewToString(new DataView(data)).trim();
            if (mythis.logCommandFn) {
              mythis.logCommandFn(replyMsg);
            }
            if (replyMsg === "OK") {
              resolve(replyMsg);
            } else {
              reject(new Error("msg not OK: " + replyMsg));
            }
          } else {
            reject(new Error("event.data not ArrayBufferLike?"));
          }
        };
        if (mythis.logCommandFn) {
          mythis.logCommandFn(mycmd);
        }
        webSocket.send(mycmd + "\r\n");
      } else {
        reject(new Error("webSocket has been closed"));
      }
    });
    return promise2;
  }
  /**
   * handle errors that arise
   *
   * @private
   * @param   error the error
   */
  handleError(error51) {
    if (this.errorHandler) {
      this.errorHandler(error51);
    } else {
      log("seedlink handleError: " + error51.message);
    }
  }
};

// src/seismogramloader.mts
var seismogramloader_exports = {};
__export(seismogramloader_exports, {
  SeismogramLoader: () => SeismogramLoader
});

// src/irisfedcatalog.mts
var IRISFEDCAT_SERVICE = "fedcatalog";
var SERVICE_VERSION5 = 1;
var SERVICE_NAME5 = `${IRISWS_PATH_BASE}-${IRISFEDCAT_SERVICE}-${SERVICE_VERSION5}`;
var TARGET_DATASELECT = "dataselect";
var FAKE_EMPTY_TEXT = "\n";
var FedCatalogDataCenter = class {
  constructor() {
    this.dataCenter = "";
    this.stationService = "";
    this.dataSelectService = "";
    this.postLines = [];
    this.services = /* @__PURE__ */ new Map();
    this.stationQuery = null;
    this.dataSelectQuery = null;
    this.level = LEVEL_NETWORK;
  }
  /**
   * Uses the response from the FedCat server to make the actual FDSNStation
   * query that returns StationXML. If the original FedCat query did not return
   * a Station service, or it was not asked for, then the array will be empty.
   *
   * @returns promise to networks
   */
  queryNetworkList() {
    if (this.stationQuery) {
      return this.stationQuery.postQuery(this.level, this.postLines);
    } else {
      return Promise.resolve([]);
    }
  }
  queryStationRawXml() {
    if (isDef(this.stationQuery)) {
      return this.stationQuery.postQueryRawXml(this.level, this.postLines);
    } else {
      throw new Error("this.stationQuery does not exist.");
    }
  }
  querySDDList() {
    if (isDef(this.dataSelectQuery)) {
      const sddList = this.postLines.map((line) => {
        const items = line.split(" ");
        const start2 = isoToDateTime(items[4]);
        const end = isoToDateTime(items[5]);
        return SeismogramDisplayData.fromCodesAndTimes(
          items[0],
          items[1],
          items[2],
          items[3],
          start2,
          end
        );
      });
      return this.dataSelectQuery.postQuerySeismograms(sddList);
    } else {
      return Promise.resolve([]);
    }
  }
};
var FedCatalogResult = class {
  constructor() {
    this.params = /* @__PURE__ */ new Map();
    this.queries = [];
  }
};
var FedCatalogQuery = class _FedCatalogQuery extends FDSNCommon {
  /**
   * Construct a query
   *
   * @param host the host to connect to , defaults to service.earthscope.org
   */
  constructor(host) {
    if (!isNonEmptyStringArg(host)) {
      host = EARTHSCOPE_HOST;
    }
    super(IRISFEDCAT_SERVICE, host);
    this._path_base = IRISWS_PATH_BASE;
    this.fedCatResult = null;
  }
  /**
   * Constructs a station FedCatalogQuery using the parameters in a StationQuery.
   *
   * @param   stationQuery query to pull parameters from
   * @returns               fedcatalog query
   */
  static fromStationQuery(stationQuery) {
    const out = new _FedCatalogQuery();
    if (!(stationQuery instanceof StationQuery)) {
      throw new Error(
        "1st arg must be a StationQuery: " + stringify(stationQuery)
      );
    }
    if (!stationQuery.isSomeParameterSet()) {
      throw new Error(
        "Some parameters must be set in the stationQuery to avoid asking for everything."
      );
    }
    if (isStringArg(stationQuery._networkCode)) {
      out.networkCode(stationQuery._networkCode);
    }
    if (isStringArg(stationQuery._stationCode)) {
      out.stationCode(stationQuery._stationCode);
    }
    if (isStringArg(stationQuery._locationCode)) {
      out.locationCode(stationQuery._locationCode);
    }
    if (isStringArg(stationQuery._channelCode)) {
      out.channelCode(stationQuery._channelCode);
    }
    if (isObject(stationQuery._startTime)) {
      out.startTime(stationQuery._startTime);
    }
    if (isObject(stationQuery._endTime)) {
      out.endTime(stationQuery._endTime);
    }
    if (isObject(stationQuery._startBefore)) {
      out.startBefore(stationQuery._startBefore);
    }
    if (isObject(stationQuery._startAfter)) {
      out.startAfter(stationQuery._startAfter);
    }
    if (isObject(stationQuery._endBefore)) {
      out.endBefore(stationQuery._endBefore);
    }
    if (isObject(stationQuery._endAfter)) {
      out.endAfter(stationQuery._endAfter);
    }
    if (isNumArg(stationQuery._minLat)) {
      out.minLat(stationQuery._minLat);
    }
    if (isNumArg(stationQuery._maxLat)) {
      out.maxLat(stationQuery._maxLat);
    }
    if (isNumArg(stationQuery._minLon)) {
      out.minLon(stationQuery._minLon);
    }
    if (isNumArg(stationQuery._maxLon)) {
      out.maxLon(stationQuery._maxLon);
    }
    if (isNumArg(stationQuery._latitude)) {
      out.latitude(stationQuery._latitude);
    }
    if (isNumArg(stationQuery._longitude)) {
      out.longitude(stationQuery._longitude);
    }
    if (isNumArg(stationQuery._minRadius)) {
      out.minRadius(stationQuery._minRadius);
    }
    if (isNumArg(stationQuery._maxRadius)) {
      out.maxRadius(stationQuery._maxRadius);
    }
    if (isDef(stationQuery._includeRestricted)) {
      out.includeRestricted(stationQuery._includeRestricted);
    }
    if (isDef(stationQuery._includeAvailability)) {
      out.includeAvailability(stationQuery._includeAvailability);
    }
    if (isObject(stationQuery._updatedAfter)) {
      out.updatedAfter(stationQuery._updatedAfter);
    }
    if (isDef(stationQuery._matchTimeseries)) {
      out.matchTimeseries(stationQuery._matchTimeseries);
    }
    return out;
  }
  /**
   * Gets/Sets the version of the fdsnws spec, 1 is currently the only value.
   *  Setting this is probably a bad idea as the code may not be compatible with
   *  the web service.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  specVersion(value) {
    doStringGetterSetter(this, "specVersion", value);
    return this;
  }
  getSpecVersion() {
    return this._specVersion;
  }
  /**
   * Gets/Sets the protocol, http or https. This should match the protocol
   *  of the page loaded, but is autocalculated and generally need not be set.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  protocol(value) {
    doStringGetterSetter(this, "protocol", value);
    return this;
  }
  getProtocol() {
    return this._protocol;
  }
  /**
   * Gets/Sets the remote host to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  host(value) {
    doStringGetterSetter(this, "host", value);
    return this;
  }
  getHost() {
    return this._host;
  }
  /**
   * Gets/Sets the remote port to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  port(value) {
    doIntGetterSetter(this, "port", value);
    return this;
  }
  getPort() {
    return this._port;
  }
  pathBase(value) {
    doStringGetterSetter(this, "path_base", value);
    return this;
  }
  getPathBase() {
    return this._path_base;
  }
  /**
   * Gets/Sets the nodata parameter, usually 404 or 204 (default), controlling
   * the status code when no matching data is found by the service.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  nodata(value) {
    doIntGetterSetter(this, "nodata", value);
    return this;
  }
  getNodata() {
    return this._nodata;
  }
  /**
   * Get/Set the targetservice query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  targetService(value) {
    doStringGetterSetter(this, "targetService", value);
    return this;
  }
  getTargetService() {
    return this._targetService;
  }
  /**
   * Get/Set the network query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  networkCode(value) {
    doStringGetterSetter(this, "networkCode", value);
    return this;
  }
  getNetworkCode() {
    return this._networkCode;
  }
  /**
   * Get/Set the station query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  stationCode(value) {
    doStringGetterSetter(this, "stationCode", value);
    return this;
  }
  getStationCode() {
    return this._stationCode;
  }
  /**
   * Get/Set the location code query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  locationCode(value) {
    doStringGetterSetter(this, "locationCode", value);
    return this;
  }
  getLocationCode() {
    return this._locationCode;
  }
  /**
   * Get/Set the channel query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  channelCode(value) {
    doStringGetterSetter(this, "channelCode", value);
    return this;
  }
  getChannelCode() {
    return this._channelCode;
  }
  nslcCodes(channelId) {
    this.networkCode(channelId.networkCode);
    this.stationCode(channelId.stationCode);
    this.locationCode(channelId.locationCode);
    this.channelCode(channelId.channelCode);
    return this;
  }
  /**
   * Get/Set the starttime query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  startTime(value) {
    doMomentGetterSetter(this, "startTime", value);
    return this;
  }
  getStartTime() {
    return this._startTime;
  }
  /**
   * Get/Set the endtime query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  endTime(value) {
    doMomentGetterSetter(this, "endTime", value);
    return this;
  }
  getEndTime() {
    return this._endTime;
  }
  /**
   * Sets startTime and endTime using the given time window
   *
   * @param   se time window
   * @returns     this
   */
  timeRange(se) {
    this.startTime(validStartTime(se));
    this.endTime(validEndTime(se));
    return this;
  }
  /**
   * Get/Set the startbefore query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  startBefore(value) {
    doMomentGetterSetter(this, "startBefore", value);
    return this;
  }
  getStartBefore() {
    return this._startBefore;
  }
  /**
   * Get/Set the endbefore query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  endBefore(value) {
    doMomentGetterSetter(this, "endBefore", value);
    return this;
  }
  getEndBefore() {
    return this._endBefore;
  }
  /**
   * Get/Set the startafter query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  startAfter(value) {
    doMomentGetterSetter(this, "startAfter", value);
    return this;
  }
  getStartAfter() {
    return this._startAfter;
  }
  /**
   * Get/Set the endafter query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  endAfter(value) {
    doMomentGetterSetter(this, "endAfter", value);
    return this;
  }
  getEndAfter() {
    return this._endAfter;
  }
  /**
   * Get/Set the minlat query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minLat(value) {
    doFloatGetterSetter(this, "minLat", value);
    return this;
  }
  getMinLat() {
    return this._minLat;
  }
  /**
   * Get/Set the maxlon query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  maxLat(value) {
    doFloatGetterSetter(this, "maxLat", value);
    return this;
  }
  getMaxLat() {
    return this._maxLat;
  }
  /**
   * Get/Set the minlon query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minLon(value) {
    doFloatGetterSetter(this, "minLon", value);
    return this;
  }
  getMinLon() {
    return this._minLon;
  }
  /**
   * Get/Set the maxlon query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  maxLon(value) {
    doFloatGetterSetter(this, "maxLon", value);
    return this;
  }
  getMaxLon() {
    return this._maxLon;
  }
  /**
   * Get/Set the latitude query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  latitude(value) {
    doFloatGetterSetter(this, "latitude", value);
    return this;
  }
  getLatitude() {
    return this._latitude;
  }
  /**
   * Get/Set the longitude query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  longitude(value) {
    doFloatGetterSetter(this, "longitude", value);
    return this;
  }
  getLongitude() {
    return this._longitude;
  }
  /**
   * Get/Set the minradius query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  minRadius(value) {
    doFloatGetterSetter(this, "minRadius", value);
    return this;
  }
  getMinRadius() {
    return this._minRadius;
  }
  /**
   * Get/Set the maxradius query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  maxRadius(value) {
    doFloatGetterSetter(this, "maxRadius", value);
    return this;
  }
  getMaxRadius() {
    return this._maxRadius;
  }
  /**
   * Get/Set the includerestricted query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  includeRestricted(value) {
    doBoolGetterSetter(this, "includeRestricted", value);
    return this;
  }
  getIncludeRestricted() {
    return this._includeRestricted;
  }
  /**
   * Get/Set the includeavailability query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  includeAvailability(value) {
    doBoolGetterSetter(this, "includeAvailability", value);
    return this;
  }
  getIncludeAvailability() {
    return this._includeAvailability;
  }
  /**
   * Get/Set the format query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  format(value) {
    doStringGetterSetter(this, "format", value);
    return this;
  }
  getFormat() {
    return this._format;
  }
  /**
   * Get/Set the updatedafter query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  updatedAfter(value) {
    doMomentGetterSetter(this, "updatedAfter", value);
    return this;
  }
  getUpdatedAfter() {
    return this._updatedAfter;
  }
  /**
   * Get/Set the matchtimeseries query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  matchTimeseries(value) {
    doBoolGetterSetter(this, "matchTimeseries", value);
    return this;
  }
  getMatchTimeseries() {
    return this._matchTimeseries;
  }
  /**
   * Get/Set the timeout in seconds for the request. Default is 30.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  timeout(value) {
    doFloatGetterSetter(this, "timeoutSec", value);
    return this;
  }
  getTimeout() {
    return this._timeoutSec;
  }
  /**
   * Checks to see if any parameter that would limit the data
   * returned is set. This is a crude, coarse check to make sure
   * the client doesn't ask for EVERYTHING the server has.
   *
   * @returns true if some parameter set
   */
  isSomeParameterSet() {
    return isDef(this._networkCode) && this._networkCode.length > 0 && this._networkCode !== "*" || isDef(this._stationCode) && this._stationCode.length > 0 && this._stationCode !== "*" || isDef(this._locationCode) && this._locationCode.length > 0 && this._locationCode !== "*" || isDef(this._channelCode) && this._channelCode.length > 0 && this._channelCode !== "*" || isDef(this._startTime) || isDef(this._endTime) || isDef(this._startBefore) || isDef(this._endBefore) || isDef(this._startAfter) || isDef(this._endAfter) || isDef(this._minLat) || isDef(this._maxLat) || isDef(this._minLon) || isDef(this._maxLon) || isDef(this._latitude) || isDef(this._longitude) || isDef(this._minRadius) || isDef(this._maxRadius) || isDef(this._updatedAfter);
  }
  /**
   * Queries the remote web service for networks.
   *
   * @returns a Promise to an Array of Network objects.
   */
  queryNetworks() {
    return this.queryFdsnStation(LEVEL_NETWORK);
  }
  /**
   * Queries the remote web service for stations. The stations
   * are contained within their respective Networks.
   *
   * @returns a Promise to an Array of Network objects.
   */
  queryStations() {
    return this.queryFdsnStation(LEVEL_STATION);
  }
  /**
   * Queries the remote web service for channels. The Channels
   * are contained within their respective Stations which are in Networks.
   *
   * @returns a Promise to an Array of Network objects.
   */
  queryChannels() {
    return this.queryFdsnStation(LEVEL_CHANNEL);
  }
  /**
   * Queries the remote web service for responses. The Responses
   * are contained within their respective Channels,
   * which are in Stations which are in Networks.
   *
   * @returns a Promise to an Array of Network objects.
   */
  queryResponses() {
    return this.queryFdsnStation(LEVEL_RESPONSE);
  }
  /**
   * Queries the remote station web service at the given level.
   *
   * @param level the level to query at, networ, station, channel or response.
   * @returns a Promise to an Array of Network objects.
   */
  queryFdsnStation(level) {
    return this.setupQueryFdsnStation(level).then((fedCatalogResult) => {
      return Promise.all(
        fedCatalogResult.queries.map((query) => query.queryNetworkList())
      );
    }).then((netArrayArray) => {
      const out = [];
      netArrayArray.forEach((netArray) => {
        netArray.forEach((net) => {
          out.push(net);
        });
      });
      return out;
    });
  }
  setupQueryFdsnStation(level) {
    if (!LEVELS.includes(level)) {
      throw new Error("Unknown level: '" + level + "'");
    }
    this._level = level;
    this.targetService("station");
    return this.queryRaw().then(function(fedCatalogResult) {
      for (const r of fedCatalogResult.queries) {
        const stationQuery = new StationQuery();
        r.stationQuery = stationQuery;
        fedCatalogResult.params.forEach((v, k) => {
          const field = `_${k}`;
          if (field === "_level") {
          } else if (field in stationQuery) {
            stationQuery[field] = v;
          } else {
            throw new Error(
              `field ${field} does not exist in StationQuery class`
            );
          }
        });
        if (!r.services.has("STATIONSERVICE") || !isDef(r.services.get("STATIONSERVICE"))) {
          throw new Error(
            "QueryResult does not have STATIONSERVICE in services"
          );
        }
        const urlString = r.services.get("STATIONSERVICE");
        if (isDef(urlString)) {
          const serviceURL = new URL(urlString);
          stationQuery.host(serviceURL.hostname);
          if (serviceURL.port) {
            stationQuery.port(parseInt(serviceURL.port));
          }
        } else {
          throw new Error(
            "QueryResult does have STATIONSERVICE in services, but is undef"
          );
        }
      }
      return fedCatalogResult;
    });
  }
  /**
   * For each item in a parsed result returned from a FedCat service, create a
   * DataSelectQuery with host and port, or url filled in correctly, ready to
   * be called with the result lines.
   *
   * @param   fedCatalogResult result from a FedCat web service
   * @returns               result with dataSelectQuery added to each item
   */
  setupForFdnsDataSelect(fedCatalogResult) {
    for (const r of fedCatalogResult.queries) {
      const dataSelectQuery = new DataSelectQuery();
      r.dataSelectQuery = dataSelectQuery;
      fedCatalogResult.params.forEach((k, v) => {
        const field = `_${k}`;
        if (field in dataSelectQuery) {
          dataSelectQuery[field] = v;
        } else {
          throw new Error(
            `field ${field} does not exist in DataSelectQuery class`
          );
        }
      });
      if (!r.services.has("DATASELECTSERVICE")) {
        throw new Error(
          "QueryResult does not have DATASELECTSERVICE in services"
        );
      }
      const urlString = r.services.get("DATASELECTSERVICE");
      if (isDef(urlString)) {
        const serviceURL = new URL(urlString);
        dataSelectQuery.host(serviceURL.hostname);
        if (serviceURL.port) {
          dataSelectQuery.port(parseInt(serviceURL.port));
        }
      } else {
        throw new Error(
          "QueryResult does have DATASELECTSERVICE in services, but is undef"
        );
      }
    }
    return fedCatalogResult;
  }
  queryFdsnDataselect() {
    this.targetService(TARGET_DATASELECT);
    return this.queryRaw().then((fedCatalogResult) => {
      return this.setupForFdnsDataSelect(fedCatalogResult);
    }).then((fedCatalogResult) => {
      return this.postFdsnDataselectForFedCatResult(fedCatalogResult);
    });
  }
  postFdsnDataselectForFedCatResult(fedCatalogResult) {
    return Promise.all(
      fedCatalogResult.queries.map((query) => query.querySDDList())
    ).then((sddArrayArray) => {
      const out = [];
      sddArrayArray.forEach((sddArray) => {
        sddArray.forEach((sdd) => {
          out.push(sdd);
        });
      });
      return out;
    });
  }
  /**
   * query the fed cat server for dataselect using post, which allows for multiple
   * channel-timeranges at once. This assumes that there are not multiple
   * time ranges for the same channel as the results, encapsulated as
   * SeismogramDisplayData objects, are returned one seismogram
   * per channel, which may contain gaps. The original channel and timerange are
   * also populated with each result.
   *
   * @param   sddList array of SeismogramDisplayData objects
   * that will be filled in with the resulting seismogram
   * @returns Promise to the input Array of SeismogramDisplayData objects, each with the
   * seismogram containing the data returned from the server
   */
  postQuerySeismograms(sddList) {
    return this.postQueryRaw(sddList, TARGET_DATASELECT).then((fedCatalogResult) => {
      this.setupForFdnsDataSelect(fedCatalogResult);
      return this.postFdsnDataselectForFedCatResult(fedCatalogResult);
    }).then((sddResultArray) => {
      for (const sdd of sddList) {
        const codes = sdd.codes();
        const matchSdd = sddResultArray.find(
          (s2) => s2.codes() === codes && s2.timeRange.overlaps(sdd.timeRange)
        );
        if (matchSdd) {
          sdd.seismogram = matchSdd.seismogram;
        }
      }
      return sddList;
    });
  }
  postQueryRaw(sddList, targetService) {
    if (sddList.length === 0) {
      return Promise.resolve(this.parseRequest(FAKE_EMPTY_TEXT));
    } else {
      const body = `targetservice=${targetService}
` + DataSelectQuery.createPostBody(sddList);
      return this.postQueryRawWithBody(body);
    }
  }
  postQueryRawWithBody(body) {
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    fetchInit.method = "POST";
    fetchInit.body = body;
    return doFetchWithTimeout(
      this.formPostURL(),
      fetchInit,
      this._timeoutSec * 1e3
    ).then((response) => {
      return this.handleHttpResponseCodes(response);
    }).then((rawText) => {
      return this.parseRequest(rawText);
    });
  }
  /**
   * Queries the remote web service.
   *
   * @returns a Promise to an parsed result.
   */
  queryRaw() {
    if (!this.isSomeParameterSet()) {
      throw new Error(
        "Must set some parameter to avoid asking for everything."
      );
    }
    const url2 = this.formURL();
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    this.fedCatResult = doFetchWithTimeout(
      url2,
      fetchInit,
      this._timeoutSec * 1e3
    ).then((response) => {
      return this.handleHttpResponseCodes(response);
    }).then((rawText) => {
      return this.parseRequest(rawText);
    });
    return this.fedCatResult;
  }
  handleHttpResponseCodes(response) {
    if (response.status === 200) {
      return response.text();
    } else if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
      return Promise.resolve(FAKE_EMPTY_TEXT);
    } else {
      throw new Error(`Status not successful: ${response.status}`);
    }
  }
  parseRequest(requestText) {
    const out = new FedCatalogResult();
    const lines = requestText.split("\n");
    let inParams = true;
    let query = null;
    for (let l2 of lines) {
      l2 = l2.trim();
      if (inParams) {
        if (l2.length === 0) {
          inParams = false;
        } else {
          const keyval = l2.split("=");
          out.params.set(keyval[0], keyval[1]);
        }
      } else {
        if (l2.length === 0) {
          query = null;
        } else {
          if (query === null) {
            query = new FedCatalogDataCenter();
            if (this._level) {
              query.level = this._level;
            }
            out.queries.push(query);
          }
          if (l2.indexOf("=") !== -1) {
            const keyval = l2.split("=");
            if (keyval[0] === "DATACENTER") {
              query.dataCenter = keyval[1];
            } else if (keyval[0].endsWith("SERVICE")) {
              query.services.set(keyval[0], keyval[1]);
            } else {
              throw new Error(`Unexpected line in FedCatalog response: '${l2}'`);
            }
          } else {
            query.postLines.push(l2);
          }
        }
      }
    }
    return out;
  }
  /**
   * Forms the URL to get version from the web service, without any query paramters
   *
   * @returns the url
   */
  formVersionURL() {
    return appendToPath(this.formBaseURL(), "version");
  }
  /**
   * Queries the remote web service to get its version
   *
   * @returns Promise to version string
   */
  queryVersion() {
    const url2 = this.formVersionURL();
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then(
      (response) => {
        if (response.status === 200) {
          return response.text();
        } else {
          throw new Error(`Status not 200: ${response.status}`);
        }
      }
    );
  }
  /**
   * Forms the base of the url for accessing the dataselect service.
   *
   * @returns         URL as string
   */
  formBaseURL() {
    let colon = ":";
    const protocol = protocolForKnownHost(this._host, this._protocol);
    if (protocol.endsWith(colon)) {
      colon = "";
    }
    const port = this.defaultPortStringForProtocol(protocol);
    const path2 = appendToPath(appendToPath(this._path_base, this._service), this._specVersion);
    return appendToPath(`${protocol}${colon}//${this._host}${port}`, path2);
  }
  /**
   * Form URL to post the remote web service. No parameters are added
   * to the URL as those will be in the body of the post.
   *
   * @returns the URL for posting
   */
  formPostURL() {
    return appendToPath(this.formBaseURL(), "query");
  }
  /**
   * Form URL to query the remote web service, encoding the query parameters.
   *
   * @returns url
   */
  formURL() {
    let url2 = appendToPath(this.formBaseURL(), "query?");
    if (isStringArg(this._level)) {
      url2 = url2 + makeParam("level", this._level);
    }
    if (isStringArg(this._targetService)) {
      url2 = url2 + makeParam("targetservice", this._targetService);
    }
    if (isStringArg(this._networkCode) && this._networkCode.length > 0 && this._networkCode !== "*") {
      url2 = url2 + makeParam("net", this._networkCode);
    } else {
      url2 = url2 + makeParam("net", "*");
    }
    if (isStringArg(this._stationCode) && this._stationCode.length > 0 && this._stationCode !== "*") {
      url2 = url2 + makeParam("sta", this._stationCode);
    }
    if (isStringArg(this._locationCode) && this._locationCode.length > 0 && this._locationCode !== "*") {
      url2 = url2 + makeParam("loc", this._locationCode);
    }
    if (isStringArg(this._channelCode) && this._channelCode.length > 0 && this._channelCode !== "*") {
      url2 = url2 + makeParam("cha", this._channelCode);
    }
    if (isObject(this._startTime)) {
      url2 = url2 + makeParam("starttime", toIsoWoZ(this._startTime));
    }
    if (isObject(this._endTime)) {
      url2 = url2 + makeParam("endtime", toIsoWoZ(this._endTime));
    }
    if (isObject(this._startBefore)) {
      url2 = url2 + makeParam("startbefore", toIsoWoZ(this._startBefore));
    }
    if (isObject(this._startAfter)) {
      url2 = url2 + makeParam("startafter", toIsoWoZ(this._startAfter));
    }
    if (isObject(this._endBefore)) {
      url2 = url2 + makeParam("endbefore", toIsoWoZ(this._endBefore));
    }
    if (isObject(this._endAfter)) {
      url2 = url2 + makeParam("endafter", toIsoWoZ(this._endAfter));
    }
    if (isNumArg(this._minLat)) {
      url2 = url2 + makeParam("minlat", this._minLat);
    }
    if (isNumArg(this._maxLat)) {
      url2 = url2 + makeParam("maxlat", this._maxLat);
    }
    if (isNumArg(this._minLon)) {
      url2 = url2 + makeParam("minlon", this._minLon);
    }
    if (isNumArg(this._maxLon)) {
      url2 = url2 + makeParam("maxlon", this._maxLon);
    }
    if (isNumArg(this._latitude)) {
      url2 = url2 + makeParam("lat", this._latitude);
    }
    if (isNumArg(this._longitude)) {
      url2 = url2 + makeParam("lon", this._longitude);
    }
    if (isNumArg(this._minRadius)) {
      url2 = url2 + makeParam("minradius", this._minRadius);
    }
    if (isNumArg(this._maxRadius)) {
      url2 = url2 + makeParam("maxradius", this._maxRadius);
    }
    if (isDef(this._includeRestricted)) {
      url2 = url2 + makeParam("includerestricted", this._includeRestricted);
    }
    if (isDef(this._includeAvailability)) {
      url2 = url2 + makeParam("includeavailability", this._includeAvailability);
    }
    if (isObject(this._updatedAfter)) {
      url2 = url2 + makeParam("updatedafter", toIsoWoZ(this._updatedAfter));
    }
    if (isDef(this._matchTimeseries)) {
      url2 = url2 + makeParam("matchtimeseries", this._matchTimeseries);
    }
    if (isStringArg(this._format)) {
      url2 = url2 + makeParam("format", this._format);
    }
    if (isNumArg(this._nodata)) {
      url2 = url2 + makeParam("nodata", this._nodata);
    }
    if (url2.endsWith("&") || url2.endsWith("?")) {
      url2 = url2.substr(0, url2.length - 1);
    }
    return url2;
  }
};

// src/seismogramloader.mts
var SeismogramLoader = class {
  constructor(stationQuery, eventQuery, dataselectQuery) {
    if (stationQuery instanceof StationQuery) {
      this.stationQuery = stationQuery;
    } else if (Array.isArray(stationQuery)) {
      this.stationQuery = Promise.resolve(stationQuery);
    } else {
      throw new Error(
        "1st arg must be a StationQuery or array of Networks: " + stringify(stationQuery)
      );
    }
    if (eventQuery instanceof EventQuery) {
      this.eventQuery = eventQuery;
    } else if (Array.isArray(eventQuery)) {
      this.eventQuery = Promise.resolve(eventQuery);
    } else {
      throw new Error(
        "2nd arg must be EventQuery or array of Quake: " + stringify(eventQuery)
      );
    }
    this.withFedCatalog = true;
    this.withResponse = false;
    this.markOrigin = true;
    this.dataselectQuery = null;
    if (isDef(dataselectQuery)) {
      this.dataselectQuery = dataselectQuery;
    }
    this._startPhaseList = ["p", "P", "Pdiff", "PKP"];
    this._endPhaseList = ["s", "S", "Sdiff", "SKS"];
    this._markedPhaseList = [];
    this._startOffset = Duration.fromMillis(-30 * 1e3);
    this._endOffset = Duration.fromMillis(60 * 1e3);
  }
  get startPhaseList() {
    return this._startPhaseList;
  }
  set startPhaseList(val) {
    if (Array.isArray(val)) {
      this._startPhaseList = val;
    } else if (isStringArg(val)) {
      this._startPhaseList = val.split(",");
    } else {
      throw new Error(
        "value argument is string or array of string, but was " + typeof val
      );
    }
  }
  get startOffset() {
    return this._startOffset;
  }
  set startOffset(val) {
    if (Duration.isDuration(val)) {
      this._startOffset = val;
    } else if (typeof val === "number") {
      this.startOffsetSeconds(val);
    } else {
      throw new Error(
        "startOffset must be luxon Duration or number of seconds: " + stringify(val)
      );
    }
  }
  /**
   * Sets the startOffset Duration to be val seconds.
   *
   * @param  val  number of seconds, negative for before, positive for after
   * @returns     this
   */
  startOffsetSeconds(val) {
    this._startOffset = Duration.fromMillis(val * 1e3);
    return this;
  }
  get endPhaseList() {
    return this._endPhaseList;
  }
  set endPhaseList(val) {
    if (Array.isArray(val)) {
      this._endPhaseList = val;
    } else if (isStringArg(val)) {
      this._endPhaseList = val.split(",");
    } else {
      throw new Error(
        "value argument is string or array of string, but was " + typeof val
      );
    }
  }
  get endOffset() {
    return this._endOffset;
  }
  set endOffset(val) {
    if (Duration.isDuration(val)) {
      this._endOffset = val;
    } else if (typeof val === "number") {
      this.endOffsetSeconds(val);
    } else {
      throw new Error(
        "startOffset must be luxon Duration or number of seconds: " + stringify(val)
      );
    }
  }
  /**
   * Sets the endOffset Duration to be val seconds.
   *
   * @param  val  number of seconds, negative for before, positive for after
   * @returns     this
   */
  endOffsetSeconds(val) {
    this._endOffset = Duration.fromMillis(val * 1e3);
    return this;
  }
  /**
   * Additional phase arrival travel times to be marked, but do not effect
   * the request time window.
   *
   * @returns array of phase names.
   */
  get markedPhaseList() {
    return this._markedPhaseList;
  }
  set markedPhaseList(val) {
    if (Array.isArray(val)) {
      this._markedPhaseList = val;
    } else if (isStringArg(val)) {
      this._markedPhaseList = val.split(",");
    } else {
      throw new Error(
        "value argument is string or array of string, but was " + typeof val
      );
    }
  }
  loadSeismograms() {
    return this.load().then((res) => res.waveforms);
  }
  /**
   * Loads a Dataset based on the input station and event queries.
   *
   * The raw traveltimes are included in the extras of the dataset with
   * key "traveltimes", which is a Map with the quake as the key.
   *
   * @returns a Dataset
   */
  load() {
    let networkListPromise;
    if (this.stationQuery instanceof StationQuery) {
      if (!this.stationQuery.isSomeParameterSet()) {
        throw new Error(
          "Must set some station parameter to avoid asking for everything."
        );
      }
      let fedcat;
      if (this.withFedCatalog) {
        fedcat = FedCatalogQuery.fromStationQuery(this.stationQuery);
      } else {
        fedcat = this.stationQuery;
      }
      if (this.withResponse) {
        networkListPromise = fedcat.queryResponses();
      } else {
        networkListPromise = fedcat.queryChannels();
      }
    } else {
      networkListPromise = this.stationQuery;
    }
    let quakeListPromise;
    if (this.eventQuery instanceof EventQuery) {
      if (!this.eventQuery.isSomeParameterSet()) {
        throw new Error(
          "Must set some event parameter to avoid asking for everything."
        );
      }
      quakeListPromise = this.eventQuery.query();
    } else {
      quakeListPromise = this.eventQuery;
    }
    let allPhaseList = [];
    allPhaseList = allPhaseList.concat(
      this.startPhaseList,
      this.endPhaseList,
      this.markedPhaseList
    );
    if (allPhaseList.includes("origin")) {
      this.markOrigin = true;
    }
    const allPhasesWithoutOrigin = allPhaseList.filter((p) => p !== "origin").join(",");
    return Promise.all([networkListPromise, quakeListPromise]).then(([netList, quakeList]) => {
      const ttpromiseList = [];
      for (const q of quakeList) {
        const allDistDeg = [];
        for (const s2 of allStations(netList)) {
          if (s2.timeRange.contains(q.time)) {
            const daz = distaz(
              s2.latitude,
              s2.longitude,
              q.latitude,
              q.longitude
            );
            allDistDeg.push(daz.distanceDeg);
          }
        }
        if (allDistDeg.length > 0) {
          const taupQuery = new TraveltimeQuery();
          taupQuery.distdeg(allDistDeg);
          taupQuery.phases(allPhasesWithoutOrigin);
          ttpromiseList.push(Promise.all([q, taupQuery.queryJson()]));
        }
      }
      return Promise.all([Promise.all(ttpromiseList), netList, quakeList]);
    }).then(([ttList, netList, quakeList]) => {
      const ttMap = /* @__PURE__ */ new Map();
      for (const [q, tt] of ttList) {
        ttMap.set(q, tt);
      }
      return Promise.all([ttMap, netList, quakeList]);
    }).then(([ttMap, netList, quakeList]) => {
      const seismogramDataList = [];
      for (const [quake, ttjson] of ttMap) {
        for (const station of allStations(netList)) {
          if (!station.timeRange.contains(quake.time)) {
            continue;
          }
          const daz = distaz(
            station.latitude,
            station.longitude,
            quake.latitude,
            quake.longitude
          );
          const stationArrivals = [];
          const DIST_TOL = 1e-4;
          for (const a of ttjson.arrivals) {
            if (Math.abs(a.distdeg % 360 - daz.distanceDeg % 360) < DIST_TOL || Math.abs(360 - a.distdeg % 360 - daz.distanceDeg % 360) < DIST_TOL) {
              stationArrivals.push(a);
            }
          }
          const station_ttjson = {
            model: ttjson.model,
            sourcedepth: ttjson.sourcedepth,
            receiverdepth: ttjson.receiverdepth,
            phases: ttjson.phases,
            arrivals: stationArrivals
          };
          let startArrival = null;
          let endArrival = null;
          for (const pname of this.startPhaseList) {
            if (pname === "origin" && (startArrival === null || startArrival.time > 0)) {
              startArrival = createOriginArrival(daz.distanceDeg);
            } else {
              for (const a of stationArrivals) {
                if (a.phase === pname && (startArrival === null || startArrival.time > a.time)) {
                  startArrival = a;
                }
              }
            }
          }
          for (const pname of this.endPhaseList) {
            if (pname === "origin" && (endArrival === null || endArrival.time < 0)) {
              endArrival = createOriginArrival(daz.distanceDeg);
            } else {
              for (const a of stationArrivals) {
                if (a.phase === pname && (endArrival === null || endArrival.time < a.time)) {
                  endArrival = a;
                }
              }
            }
          }
          if (isDef(startArrival) && isDef(endArrival)) {
            const startTime = quake.time.plus(Duration.fromMillis(1e3 * startArrival.time)).plus(this.startOffset);
            const endTime = quake.time.plus(Duration.fromMillis(1e3 * endArrival.time)).plus(this.endOffset);
            const timeRange = Interval.fromDateTimes(startTime, endTime);
            const phaseMarkers = createMarkersForTravelTimes(
              quake,
              station_ttjson
            );
            if (this.markOrigin) {
              phaseMarkers.push(createMarkerForOriginTime(quake));
            }
            for (const chan of station.channels) {
              if (!chan.timeRange.contains(quake.time)) {
                continue;
              }
              const sdd = SeismogramDisplayData.fromChannelAndTimeWindow(
                chan,
                timeRange
              );
              sdd.addQuake(quake);
              sdd.addTravelTimes(ttjson);
              sdd.addMarkers(phaseMarkers);
              seismogramDataList.push(sdd);
            }
          }
        }
      }
      let sddListPromise;
      if (this.dataselectQuery !== null) {
        sddListPromise = this.dataselectQuery.postQuerySeismograms(seismogramDataList);
      } else if (this.withFedCatalog) {
        const fedcatDS = new FedCatalogQuery();
        sddListPromise = fedcatDS.postQuerySeismograms(seismogramDataList);
      } else {
        sddListPromise = new DataSelectQuery().postQuerySeismograms(
          seismogramDataList
        );
      }
      return Promise.all([sddListPromise, ttMap, netList, quakeList]);
    }).then(([sddList, ttMap, networkList, quakeList]) => {
      const dataset = new Dataset();
      dataset.waveforms = sddList;
      dataset.catalog = quakeList;
      dataset.inventory = networkList;
      dataset.extra.set("traveltimes", ttMap);
      return dataset;
    });
  }
};

// src/seismographconfigeditor.mts
var seismographconfigeditor_exports = {};
__export(seismographconfigeditor_exports, {
  configEditor_css: () => configEditor_css,
  createEditor: () => createEditor
});
function createEditor(div, config2, onChange) {
  if (!isDef(div)) {
    throw new Error("div is Required");
  }
  if (!isDef(onChange)) {
    onChange = () => {
    };
  }
  const titleDiv = div.append("div");
  createBooleanOptionByKey(
    titleDiv.append("span"),
    "",
    "showTitle",
    config2,
    onChange
  );
  createTextOption(titleDiv.append("span"), "Title", "title", config2, onChange);
  titleDiv.selectAll("input").classed("smallconfigtext", false).classed("bigconfigtext", true);
  const xLabelDiv = div.append("div");
  xLabelDiv.append("span").text("X Axis:");
  createBooleanOptionByKey(
    xLabelDiv.append("span"),
    "Bot",
    "isXAxis",
    config2,
    onChange
  );
  createBooleanOptionByKey(
    xLabelDiv.append("span"),
    "Top",
    "isXAxisTop",
    config2,
    onChange
  );
  createTextOption(
    xLabelDiv.append("span"),
    "X Label",
    "xLabel",
    config2,
    onChange
  );
  createTextOption(
    xLabelDiv.append("span"),
    "Sublabel",
    "xSublabel",
    config2,
    onChange
  );
  createBooleanOptionByKey(
    xLabelDiv.append("span"),
    "Relative",
    "isRelativeTime",
    config2,
    onChange
  );
  const yLabelDiv = div.append("div");
  yLabelDiv.append("span").text("Y Axis:");
  createBooleanOptionByKey(
    yLabelDiv.append("span"),
    "Left",
    "isYAxis",
    config2,
    onChange
  );
  createBooleanOptionByKey(
    yLabelDiv.append("span"),
    "Right",
    "isYAxisRight",
    config2,
    onChange
  );
  createTextOption(
    yLabelDiv.append("span"),
    "Label",
    "yLabel",
    config2,
    onChange
  );
  createTextOption(
    yLabelDiv.append("span"),
    " Sublabel",
    "ySublabel",
    config2,
    onChange
  );
  createBooleanOptionByKey(
    yLabelDiv.append("span"),
    "is Units",
    "ySublabelIsUnits",
    config2,
    onChange
  );
  const yLabelDivB = div.append("div");
  createBooleanOptionByKey(
    yLabelDivB.append("span"),
    "Nice",
    "isYAxisNice",
    config2,
    onChange
  );
  createBooleanOptionByKey(
    yLabelDivB.append("span"),
    "Window",
    "windowAmp",
    config2,
    onChange
  );
  const marginDiv = div.append("div");
  marginDiv.append("label").text("Margin:");
  createNumberOption(
    marginDiv.append("span"),
    "Left",
    "left",
    config2.margin,
    onChange
  );
  createNumberOption(
    marginDiv.append("span"),
    "Right",
    "right",
    config2.margin,
    onChange
  );
  createNumberOption(
    marginDiv.append("span"),
    "Top",
    "top",
    config2.margin,
    onChange
  );
  createNumberOption(
    marginDiv.append("span"),
    "Bottom",
    "bottom",
    config2.margin,
    onChange
  );
  const colorDiv = div.append("div");
  colorDiv.append("label").text("Color:");
  let colorLineNum = 0;
  const perLine = 5;
  while (colorLineNum * perLine < config2.lineColors.length) {
    const subDiv = colorDiv.append("div");
    config2.lineColors.slice(colorLineNum * perLine, colorLineNum * perLine + perLine).forEach((color2, index) => {
      const colorspan = subDiv.append("span");
      const cindex = index + colorLineNum * perLine;
      colorspan.style("color", color2);
      colorspan.append("label").text(`${cindex + 1}:`);
      colorspan.append("input").classed("smallconfigtext", true).attr("type", "text").attr("name", `color${cindex + 1}`).property("value", color2).on("change", function() {
        const val = select_default2(this).property("value");
        config2.lineColors[cindex] = val;
        colorspan.style("color", val);
        colorspan.select("input").style("color", val);
        onChange();
      });
      colorspan.select("input").style("color", color2);
    });
    colorLineNum += 1;
  }
  createNumberOption(
    div.append("div"),
    "Line Width",
    "lineWidth",
    config2,
    onChange
  );
  createBooleanOptionByKey(
    div.append("div"),
    "Connect Segments",
    "connectSegments",
    config2,
    onChange
  );
  createBooleanOptionByKey(
    div.append("div"),
    "Show Markers",
    "doMarkers",
    config2,
    onChange
  );
  const heightDiv = div.append("div");
  heightDiv.append("label").text("Height:");
  const subHeightDiv = heightDiv.append("span");
  createNumberOption(
    subHeightDiv.append("span"),
    "Min",
    "minHeight",
    config2,
    onChange
  );
  createNumberOption(
    subHeightDiv.append("span"),
    "Max",
    "maxHeight",
    config2,
    onChange
  );
  createBooleanOptionByKey(
    div.append("div"),
    "Mouse Wheel Zoom",
    "wheelZoom",
    config2,
    onChange
  );
}
function createBooleanOptionByKey(myspan, label, key, config2, onChange) {
  myspan.append("input").attr("type", "checkbox").attr("id", key).attr("name", key).property("checked", config2[key]).on("change", function() {
    config2[key] = select_default2(this).property("checked");
    onChange();
  });
  myspan.append("label").text(`${label}:`);
  return myspan;
}
function createTextOption(mydiv, label, key, config2, onChange) {
  const myspan = mydiv.append("span");
  myspan.append("label").text(`${label}:`);
  myspan.append("input").classed("smallconfigtext", true).attr("type", "text").attr("id", key).attr("name", key).property("value", config2[key]).on("change", function() {
    config2[key] = select_default2(this).property("value");
    onChange();
  });
  return myspan;
}
function createNumberOption(mydiv, label, key, config2, onChange) {
  const myspan = mydiv.append("span");
  myspan.append("label").text(`${label}:`);
  myspan.append("input").classed("smallconfigtext", true).attr("type", "number").attr("id", key).attr("name", key).property("value", config2[key]).on("change", function() {
    config2[key] = Number.parseInt(select_default2(this).property("value"));
    onChange();
  });
  return myspan;
}
var configEditor_css = `
input[type="text"].smallconfigtext {
  width: 7em;
}

input[type="number"].smallconfigtext {
  width: 7em;
}

input[type="text"].bigconfigtext {
  width: 27em;
}
`;
if (document) {
  insertCSS(configEditor_css, "configeditor");
}

// src/syngine.mts
var syngine_exports = {};
__export(syngine_exports, {
  SERVICE_NAME: () => SERVICE_NAME6,
  SERVICE_VERSION: () => SERVICE_VERSION6,
  SYNGINE_SERVICE: () => SYNGINE_SERVICE,
  SyngineQuery: () => SyngineQuery,
  calcMoment: () => calcMoment
});
var SYNGINE_SERVICE = "syngine";
var SERVICE_VERSION6 = 1;
var SERVICE_NAME6 = `${IRISWS_PATH_BASE}-${SYNGINE_SERVICE}-${SERVICE_VERSION6}`;
function calcMoment(Mw) {
  return 10 ** (Mw / 2 * 3 + 9.1);
}
var SyngineQuery = class extends FDSNCommon {
  constructor(host) {
    if (!isNonEmptyStringArg(host)) {
      host = EARTHSCOPE_HOST;
    }
    super(SYNGINE_SERVICE, host);
    this._path_base = IRISWS_PATH_BASE;
  }
  /**
   * Gets/Sets the version of the syngine spec, 1 is currently the only value.
   *  Setting this is probably a bad idea as the code may not be compatible with
   *  the web service.
   *
   * @param value spec version, usually 1
   * @returns new value if getting, this if setting
   */
  specVersion(value) {
    doStringGetterSetter(this, "specVersion", value);
    return this;
  }
  getSpecVersion() {
    return this._specVersion;
  }
  /**
   * Gets/Sets the protocol, http or https. This should match the protocol
   *  of the page loaded, but is autocalculated and generally need not be set.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  protocol(value) {
    doStringGetterSetter(this, "protocol", value);
    return this;
  }
  getProtocol() {
    return this._protocol;
  }
  /**
   * Gets/Sets the remote host to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  host(value) {
    doStringGetterSetter(this, "host", value);
    return this;
  }
  getHost() {
    return this._host;
  }
  /**
   * Gets/Sets the nodata parameter, usually 404 or 204 (default), controlling
   * the status code when no matching data is found by the service.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  nodata(value) {
    doIntGetterSetter(this, "nodata", value);
    return this;
  }
  getNodata() {
    return this._nodata;
  }
  /**
   * Gets/Sets the remote port to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  port(value) {
    doIntGetterSetter(this, "port", value);
    return this;
  }
  getPort() {
    return this._port;
  }
  pathBase(value) {
    doStringGetterSetter(this, "path_base", value);
    return this;
  }
  getPathBase() {
    return this._path_base;
  }
  format(value) {
    doStringGetterSetter(this, "format", value);
    return this;
  }
  getFormat() {
    return this._label;
  }
  /**
   * Get/Set the model query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  model(value) {
    doStringGetterSetter(this, "model", value);
    return this;
  }
  getModel() {
    return this._model;
  }
  /**
   * Get/Set the label query parameter, used for file names.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  label(value) {
    doStringGetterSetter(this, "label", value);
    return this;
  }
  getLabel() {
    return this._label;
  }
  /**
   * Get/Set the components query parameter, used for file names.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  components(value) {
    doStringGetterSetter(this, "components", value);
    return this;
  }
  getComponents() {
    return this._components;
  }
  /**
   * Get/Set the units query parameter, displacement, velocity or acceleration.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  units(value) {
    doStringGetterSetter(this, "units", value);
    return this;
  }
  getUnits() {
    return this._units;
  }
  /**
   * Gets/Sets the dt query parameter, for upsampling.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  dt(value) {
    doIntGetterSetter(this, "dt", value);
    return this;
  }
  getDt() {
    return this._dt;
  }
  /**
   * Gets/Sets the scale query parameter, for upsampling.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  scale(value) {
    doFloatGetterSetter(this, "scale", value);
    return this;
  }
  getscale() {
    return this._scale;
  }
  /**
   * Gets/Sets the kernelwidth query parameter, for upsampling.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  kernelWidth(value) {
    doFloatGetterSetter(this, "kernelwidth", value);
    return this;
  }
  getKernelWidth() {
    return this._kernelwidth;
  }
  /**
   * Gets/Sets the sourcewidth query parameter, for upsampling.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  sourceWidth(value) {
    doFloatGetterSetter(this, "sourcewidth", value);
    return this;
  }
  getSourceWidth() {
    return this._sourcewidth;
  }
  /**
   * Get/Set the origintime query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  originTime(value) {
    doMomentGetterSetter(this, "originTime", value);
    return this;
  }
  getOriginTime() {
    return this._originTime;
  }
  /**
   * Get/Set the starttime query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  startTime(value) {
    doMomentGetterSetter(this, "startTime", value);
    return this;
  }
  getStartTime() {
    return this._startTime;
  }
  /**
   * Get/Set the endtime query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  endTime(value) {
    doMomentGetterSetter(this, "endTime", value);
    return this;
  }
  getEndTime() {
    return this._endTime;
  }
  /**
   * Get/Set the network query parameter, used for receiver location.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  network(value) {
    doStringGetterSetter(this, "network", value);
    return this;
  }
  getNetwork() {
    return this._network;
  }
  /**
   * Get/Set the station query parameter, used for receiver location.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  station(value) {
    doStringGetterSetter(this, "station", value);
    return this;
  }
  getStation() {
    return this._station;
  }
  /**
   * Get/Set the network query parameter, code used for synthetics.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  networkCode(value) {
    doStringGetterSetter(this, "networkCode", value);
    return this;
  }
  getNetworkCode() {
    return this._networkCode;
  }
  /**
   * Get/Set the station query parameter, code used for synthetics.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  stationCode(value) {
    doStringGetterSetter(this, "stationCode", value);
    return this;
  }
  getStationCode() {
    return this._stationCode;
  }
  /**
   * Get/Set the location code query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  locationCode(value) {
    doStringGetterSetter(this, "locationCode", value);
    return this;
  }
  getLocationCode() {
    return this._locationCode;
  }
  /**
   * Get/Set the receiverlatitude query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  receiverLatitude(value) {
    doFloatGetterSetter(this, "receiverlatitude", value);
    return this;
  }
  getReceiverLatitude() {
    return this._receiverlatitude;
  }
  /**
   * Get/Set the receiverlongitude query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  receiverLongitude(value) {
    doFloatGetterSetter(this, "receiverlongitude", value);
    return this;
  }
  getReceiverLongitude() {
    return this._receiverlongitude;
  }
  channel(chan) {
    this._channel = chan;
    return this;
  }
  getChannel() {
    return this._channel;
  }
  /**
   * Get/Set the eventid query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  eventId(value) {
    doStringGetterSetter(this, "eventid", value);
    return this;
  }
  getEventId() {
    return this._eventid;
  }
  quake(quake) {
    this._quake = quake;
    return this;
  }
  getQuake() {
    return this._quake;
  }
  /**
   * Get/Set the sourcelatitude query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  sourceLatitude(value) {
    doFloatGetterSetter(this, "sourcelatitude", value);
    return this;
  }
  getSourceLatitude() {
    return this._sourcelatitude;
  }
  /**
   * Get/Set the longitude query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  sourceLongitude(value) {
    doFloatGetterSetter(this, "sourcelongitude", value);
    return this;
  }
  getSourceLongitude() {
    return this._sourcelongitude;
  }
  /**
   * Get/Set the sourcedepthinmeters query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  sourceDepthInMeters(value) {
    doFloatGetterSetter(this, "sourcedepthinmeters", value);
    return this;
  }
  getSourceDepthInMeters() {
    return this._sourcedepthinmeters;
  }
  /**
   * Get/Set the sourcedistanceindegrees query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  sourceDistanceInDegrees(value) {
    doFloatGetterSetter(this, "sourcedistanceindegrees", value);
    return this;
  }
  getSourceDistanceInDegrees() {
    return this._sourcedistanceindegrees;
  }
  /**
   * Get/Set the sourcemomenttensorb query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  sourceMomentTensor(value) {
    if (value && value.length !== 6) {
      throw new Error(`Moment tensor must be 6 numbers, but given ${value.length}`);
    }
    this._sourcemomenttensor = value;
    return this;
  }
  getSourceMomentTensor() {
    return this._sourcemomenttensor;
  }
  /**
   * Get/Set the sourcedoublecouple query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  sourceDoubleCouple(value) {
    if (value && (value.length !== 3 && value.length !== 4)) {
      throw new Error(`Moment tensor must be 3-4 numbers, but given ${value.length}`);
    }
    this._sourcedoublecouple = value;
    return this;
  }
  getSourceDoubleCouple() {
    return this._sourcedoublecouple;
  }
  /**
   * Get/Set the sourceforce query parameter.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  sourceForce(value) {
    if (value && value.length !== 3) {
      throw new Error(`sourceforce must be 3 numbers, but given ${value.length}`);
    }
    this._sourceforce = value;
    return this;
  }
  getSsourceForce() {
    return this._sourceforce;
  }
  // USGS Finite Fault
  // Todo
  // Custom Source Time Function
  // Todo
  /**
   * queries the web service using the configured parameters, parsing the response
   * into miniseed data records.
   *
   * @returns Promise to Array of miniseed.DataRecords
   */
  queryDataRecords() {
    this.format(FORMAT_MINISEED);
    const url2 = this.formURL();
    const fetchInit = defaultFetchInitObj(MINISEED_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 204 || isDef(this._nodata) && response.status === this.getNodata()) {
        return new ArrayBuffer(0);
      } else {
        return response.arrayBuffer();
      }
    }).then(function(rawBuffer) {
      const dataRecords = parseDataRecords(rawBuffer);
      for (const dr of dataRecords) {
        const ms2Data = dr.decompress();
        let max = 0;
        for (let i = 0; i < ms2Data.length; i++) {
          if (ms2Data[i] > max) {
            max = ms2Data[i];
          }
        }
      }
      return dataRecords;
    });
  }
  /**
   * queries the web service using the configured parameters, parsing the response
   * into miniseed2 data records, then convert to MSeed3Records populating
   * extra headers.
   *
   * @returns Promise to Array of mseed3.MSeed3Record
   */
  queryMS3Records() {
    return this.queryDataRecords().then((msList) => {
      const ms3List = convertMS2toMSeed3(msList);
      return ms3List;
    });
  }
  /**
   * queries the web service using the configured parameters, parsing the response
   * into miniseed data records and then combining the data records into
   * SeismogramDisplayData objects.
   *
   * @returns Promise to Array of SeismogramDisplayData objects
   */
  querySeismograms() {
    return this.queryMS3Records().then((dataRecords) => {
      const sddList = sddPerChannel(dataRecords);
      const quake = this.getQuake();
      let yunit = "count";
      const queryUnits = this.getUnits();
      if (queryUnits === "displacement") {
        yunit = "m";
      } else if (queryUnits === "velocity") {
        yunit = "m/s";
      } else if (queryUnits === "acceleration") {
        yunit = "m/s2";
      }
      for (const sdd of sddList) {
        if (quake) {
          sdd.addQuake(quake);
        }
        const segments = sdd.seismogram ? sdd.seismogram.segments : [];
        for (const seg of segments) {
          seg.yUnit = yunit;
        }
      }
      return sddList;
    });
  }
  /**
   * Forms the basic URL to contact the web service, without any query paramters
   *
   * @returns the url
   */
  formBaseURL() {
    let colon = ":";
    const protocol = protocolForKnownHost(this._host, this._protocol);
    if (protocol.endsWith(colon)) {
      colon = "";
    }
    const port = this.defaultPortStringForProtocol(protocol);
    const path2 = `${this._path_base}/${this._service}/${this._specVersion}`;
    return appendToPath(`${protocol}${colon}//${this._host}${port}`, path2);
  }
  formVersionURL() {
    return appendToPath(this.formBaseURL(), "version");
  }
  /**
   * Queries the remote web service to get its version
   *
   * @returns Promise to version string
   */
  queryVersion() {
    const url2 = this.formVersionURL();
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then(
      (response) => {
        if (response.status === 200) {
          return response.text();
        } else {
          throw new Error(`Status not 200: ${response.status}`);
        }
      }
    );
  }
  formURL() {
    let url2 = appendToPath(this.formBaseURL(), "query?");
    if (isStringArg(this._model) && this._model.length > 0) {
      url2 = url2 + makeParam("model", this._model);
    }
    if (isStringArg(this._label) && this._label.length > 0) {
      url2 = url2 + makeParam("label", this._label);
    }
    if (isStringArg(this._components) && this._components.length > 0) {
      url2 = url2 + makeParam("components", this._components);
    }
    if (isStringArg(this._units) && this._units.length > 0) {
      url2 = url2 + makeParam("units", this._units);
    }
    if (isNumArg(this._dt)) {
      url2 = url2 + makeParam("dt", this._dt);
    }
    if (isNumArg(this._scale)) {
      url2 = url2 + makeParam("scale", this._scale);
    }
    if (isNumArg(this._kernelwidth)) {
      url2 = url2 + makeParam("kernelwidth", this._kernelwidth);
    }
    if (isNumArg(this._sourcewidth)) {
      url2 = url2 + makeParam("sourcewidth", this._sourcewidth);
    }
    if (isObject(this._startTime)) {
      url2 = url2 + makeParam("starttime", toIsoWoZ(this._startTime));
    }
    if (isObject(this._endTime)) {
      url2 = url2 + makeParam("endtime", toIsoWoZ(this._endTime));
    }
    if (this._channel && this._channel.networkCode !== TESTING_NETWORK) {
      url2 = url2 + makeParam("network", this._channel.networkCode) + makeParam("station", this._channel.stationCode);
    } else if (isNumArg(this._receiverlatitude) && isNumArg(this._receiverlongitude)) {
      url2 = url2 + makeParam("receiverlatitude", this._receiverlatitude) + makeParam("receiverlongitude", this._receiverlongitude);
    } else if (isStringArg(this._network) && this._network.length > 0 && isStringArg(this._station) && this._station.length > 0) {
      url2 = url2 + makeParam("network", this._network) + makeParam("station", this._station);
    } else {
      if (isStringArg(this._networkCode) && this._networkCode.length > 0 && this._networkCode !== "*") {
        url2 = url2 + makeParam("networkcode", this._networkCode);
      }
      if (isStringArg(this._stationCode) && this._stationCode.length > 0 && this._stationCode !== "*") {
        url2 = url2 + makeParam("stationcode", this._stationCode);
      }
    }
    if (isStringArg(this._locationCode) && this._locationCode.length > 0 && this._locationCode !== "*") {
      url2 = url2 + makeParam("loc", this._locationCode);
    }
    if (this._quake) {
      url2 = url2 + makeParam("origintime", this._quake.time);
      url2 = url2 + makeParam("sourcelatitude", this._quake.latitude) + makeParam("sourcelongitude", this._quake.longitude);
      url2 = url2 + makeParam("sourcedepthinmeters", this._quake.depth);
    } else if (isStringArg(this._eventid)) {
      url2 = url2 + makeParam("eventid", this._eventid);
    } else {
      if (isObject(this._originTime)) {
        url2 = url2 + makeParam("origintime", toIsoWoZ(this._originTime));
      }
      if (isNumArg(this._sourcelatitude) && isNumArg(this._sourcelongitude)) {
        url2 = url2 + makeParam("sourcelatitude", this._sourcelatitude) + makeParam("sourcelongitude", this._sourcelongitude);
      } else if (isNumArg(this._sourcedistanceindegrees)) {
        url2 = url2 + makeParam("sourcedistanceindegrees", this._sourcedistanceindegrees);
      }
      if (isNumArg(this._sourcedepthinmeters)) {
        url2 = url2 + makeParam("sourcedepthinmeters", this._sourcedepthinmeters);
      }
    }
    if (isDef(this._sourcemomenttensor)) {
      url2 = url2 + makeParam("sourcemomenttensor", this._sourcemomenttensor.join(","));
    } else if (isDef(this._sourcedoublecouple)) {
      url2 = url2 + makeParam("sourcedoublecouple", this._sourcedoublecouple.join(","));
    } else if (isDef(this._sourceforce)) {
      url2 = url2 + makeParam("sourceforce", this._sourceforce.join(","));
    } else if (isDef(this._quake)) {
      if (isDef(this._quake.preferredFocalMechanism?.momentTensorList) && this._quake.preferredFocalMechanism.momentTensorList.length > 0) {
        const focMech = this._quake.preferredFocalMechanism;
        const mt = focMech.momentTensorList[0];
        if (isDef(mt.tensor)) {
          const t = mt.tensor;
          url2 = url2 + makeParam("sourcemomenttensor", `${t.Mrr.value},${t.Mtt.value},${t.Mpp.value},${t.Mrt.value},${t.Mrp.value},${t.Mtp.value}`);
        }
      } else if (isDef(this._quake?.preferredFocalMechanism?.nodalPlanes)) {
        const np = this._quake?.preferredFocalMechanism?.nodalPlanes.nodalPlane1;
        const magVal = this._quake?.preferredMagnitude?.magQuantity?.value;
        const momentArg = isDef(magVal) ? `,${calcMoment(magVal)}` : "";
        if (isDef(np)) {
          url2 = url2 + makeParam("sourcedoublecouple", `${np.strike.value},${np.dip.value},${np.rake.value}${momentArg}`);
        }
      }
    }
    if (this._format) {
      url2 = url2 + makeParam("format", this._format);
    }
    if (this._nodata) {
      url2 = url2 + makeParam("nodata", this._nodata);
    }
    if (url2.endsWith("&") || url2.endsWith("?")) {
      url2 = url2.substr(0, url2.length - 1);
    }
    return url2;
  }
};

// src/taper.mts
var taper_exports = {};
__export(taper_exports, {
  COSINE: () => COSINE,
  HAMMING: () => HAMMING,
  HANNING: () => HANNING,
  getCoefficients: () => getCoefficients,
  taper: () => taper
});
function taper(seis, width = 0.05, taperType = HANNING) {
  if (width > 0.5) {
    throw new Error(`Taper width cannot be larger than 0.5, width=${width}`);
  }
  if (seis.isContiguous()) {
    const data = seis.y;
    const outData = Float32Array.from(data);
    const w = Math.floor(data.length * width);
    const coeff = getCoefficients(taperType, w);
    const omega = coeff[0];
    const f0 = coeff[1];
    const f1 = coeff[2];
    for (let i = 0; i < w; i++) {
      const taperFactor = f0 - f1 * Math.cos(omega * i);
      outData[i] = outData[i] * taperFactor;
      outData[outData.length - i - 1] = outData[outData.length - i - 1] * taperFactor;
    }
    return seis.cloneWithNewData(outData);
  } else {
    throw new Error(
      `Cannot take taper of non-contiguous seismogram: ${seis.segments.length}`
    );
  }
}
function getCoefficients(type, length) {
  let omega, f0, f1;
  if (type === HANNING) {
    omega = Math.PI / length;
    f0 = 0.5;
    f1 = 0.5;
  } else if (type === HAMMING) {
    omega = Math.PI / length;
    f0 = 0.54;
    f1 = 0.46;
  } else {
    omega = Math.PI / 2 / length;
    f0 = 1;
    f1 = 1;
  }
  return [omega, f0, f1];
}
var HANNING = "HANNING";
var HAMMING = "HAMMING";
var COSINE = "COSINE";

// src/taup3.mts
var taup3_exports = {};
__export(taup3_exports, {
  FAKE_EMPTY_SVG: () => FAKE_EMPTY_SVG2,
  FAKE_EMPTY_TEXT_HEADERS: () => FAKE_EMPTY_TEXT_HEADERS2,
  FAKE_EMPTY_TEXT_MODEL: () => FAKE_EMPTY_TEXT_MODEL2,
  JSON_FORMAT: () => JSON_FORMAT2,
  SVG_FORMAT: () => SVG_FORMAT2,
  TAUP_PATH_TOOL: () => TAUP_PATH_TOOL,
  TAUP_SERVICE: () => TAUP_SERVICE,
  TAUP_TIME_TOOL: () => TAUP_TIME_TOOL,
  TEXT_FORMAT: () => TEXT_FORMAT2,
  TauPQuery: () => TauPQuery,
  USC_HOST: () => USC_HOST,
  createEmptyTraveltimeJson: () => createEmptyTraveltimeJson2,
  createOriginArrival: () => createOriginArrival2,
  isValidTauP3TimeJsonType: () => isValidTauP3TimeJsonType,
  isValidTraveltimeArrivalType: () => isValidTraveltimeArrivalType2
});
var USC_HOST = "www.seis.sc.edu";
var TEXT_FORMAT2 = "text";
var JSON_FORMAT2 = "json";
var SVG_FORMAT2 = "svg";
var TAUP_SERVICE = "taup";
var TAUP_TIME_TOOL = "time";
var TAUP_PATH_TOOL = "path";
function isValidTauP3TimeJsonType(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  if (!(typeof object2.model === "string") && Array.isArray(object2.phases) && Array.isArray(object2.arrivals)) {
    return false;
  }
  if (typeof object2.sourceDepth === "number") {
    object2.sourcedepthlist = [object2.sourceDepth];
    object2.sourceDepth = void 0;
  }
  if (typeof object2.receiverDepth === "number") {
    object2.receiverdepthlist = [object2.receiverDepth];
    object2.receiverDepth = void 0;
  }
  if (typeof object2.sourcedepth === "number") {
    object2.sourcedepthlist = [object2.sourcedepth];
    object2.sourcedepth = void 0;
  }
  if (typeof object2.receiverdepth === "number") {
    object2.receiverdepthlist = [object2.receiverdepth];
    object2.receiverdepth = void 0;
  }
  if (!(Array.isArray(object2.sourcedepthlist) && Array.isArray(object2.receiverdepthlist))) {
    return false;
  }
  return true;
}
function isValidTraveltimeArrivalType2(v) {
  if (!v || typeof v !== "object") {
    return false;
  }
  const object2 = v;
  return typeof object2.sourcedepth === "number" && typeof object2.receiverdepth === "number" && typeof object2.distdeg === "number" && typeof object2.name === "string" && typeof object2.time === "number" && typeof object2.rayparam === "number" && typeof object2.takeoff === "number" && typeof object2.incident === "number" && typeof object2.puristdist === "number" && typeof object2.puristname === "string";
}
function createOriginArrival2(distdeg) {
  return {
    sourcedepth: 0,
    receiverdepth: 0,
    distdeg,
    phase: "origin",
    time: 0,
    rayparam: 0,
    takeoff: 0,
    incident: 0,
    puristdist: distdeg,
    puristname: "origin"
  };
}
var TauPQuery = class extends FDSNCommon {
  constructor(host) {
    if (!isNonEmptyStringArg(host)) {
      host = USC_HOST;
    }
    super(TAUP_SERVICE, host);
    this.specVersion("3");
    this._path_base = LOCALWS_PATH_BASE;
    this._evdepth = [0];
    this._format = JSON_FORMAT2;
    this._noheader = false;
  }
  protocol(value) {
    doStringGetterSetter(this, "protocol", value);
    return this;
  }
  getProtocol() {
    return this._protocol;
  }
  host(value) {
    doStringGetterSetter(this, "host", value);
    return this;
  }
  getHost() {
    return this._host;
  }
  /**
   * Gets/Sets the remote port to connect to.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  port(value) {
    doIntGetterSetter(this, "port", value);
    return this;
  }
  getPort() {
    return this._port;
  }
  pathBase(value) {
    doStringGetterSetter(this, "path_base", value);
    return this;
  }
  getPathBase() {
    return this._path_base;
  }
  /**
   * Gets/Sets the nodata parameter, usually 404 or 204 (default), controlling
   * the status code when no matching data is found by the service.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  nodata(value) {
    doIntGetterSetter(this, "nodata", value);
    return this;
  }
  getNodata() {
    return this._nodata;
  }
  specVersion(value) {
    doStringGetterSetter(this, "specVersion", value);
    return this;
  }
  getSpecVersion() {
    return this._specVersion;
  }
  evdepth(value) {
    if (typeof value === "number") {
      this._evdepth = [value];
    } else {
      this._evdepth = value;
    }
    return this;
  }
  evdepthInMeter(value) {
    if (value == null) {
      this._evdepth = [];
    } else if (typeof value === "number") {
      this._evdepth = [value / 1e3];
    } else {
      this._evdepth = value.map((d) => d / 1e3);
    }
    return this;
  }
  getEvdepth() {
    return this._evdepth;
  }
  distdeg(value) {
    if (typeof value === "number") {
      this._distdeg = [value];
    } else {
      this._distdeg = value;
    }
    return this;
  }
  getDistdeg() {
    return this._distdeg;
  }
  model(value) {
    doStringGetterSetter(this, "model", value);
    return this;
  }
  getModel() {
    return this._model;
  }
  phases(value) {
    doStringGetterSetter(this, "phases", value);
    return this;
  }
  getPhases() {
    return this._phases;
  }
  stalat(value) {
    doFloatGetterSetter(this, "stalat", value);
    return this;
  }
  getStalat() {
    return this._stalat;
  }
  stalon(value) {
    doFloatGetterSetter(this, "stalon", value);
    return this;
  }
  getStalon() {
    return this._stalon;
  }
  latLonFromStation(station) {
    this.stalat(station.latitude);
    this.stalon(station.longitude);
    return this;
  }
  receiverdepth(value) {
    doFloatGetterSetter(this, "receiverdepth", value);
    return this;
  }
  receiverdepthInMeter(value) {
    doFloatGetterSetter(
      this,
      "receiverdepth",
      isDef(value) ? value / 1e3 : value
    );
    return this;
  }
  receiverdepthFromChannel(channel) {
    return this.receiverdepth(channel.depth / 1e3);
  }
  getReceiverdepth() {
    return this._receiverdepth;
  }
  evlat(value) {
    doFloatGetterSetter(this, "evlat", value);
    return this;
  }
  getEvlat() {
    return this._evlat;
  }
  evlon(value) {
    doFloatGetterSetter(this, "evlon", value);
    return this;
  }
  getEvlon() {
    return this._evlon;
  }
  latLonFromQuake(quake) {
    this.evlat(quake.latitude);
    this.evlon(quake.longitude);
    this.evdepthInMeter(quake.depth);
    return this;
  }
  format(value) {
    doStringGetterSetter(this, "format", value);
    return this;
  }
  getFormat() {
    return this._format;
  }
  noheader(value) {
    doBoolGetterSetter(this, "noheader", value);
    return this;
  }
  getNoheader() {
    return this._noheader;
  }
  /**
   * Get/Set the timeout in seconds for the request. Default is 30.
   *
   * @param value optional new value if setting
   * @returns new value if getting, this if setting
   */
  timeout(value) {
    doFloatGetterSetter(this, "timeoutSec", value);
    return this;
  }
  getTimeout() {
    return this._timeoutSec;
  }
  queryText() {
    this.format(TEXT_FORMAT2);
    const url2 = this.formURL(TAUP_TIME_TOOL);
    const fetchInit = defaultFetchInitObj(TEXT_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then(
      (response) => {
        if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
          return FAKE_EMPTY_TEXT_MODEL2 + (isDef(this._model) ? this.getModel() : "") + FAKE_EMPTY_TEXT_HEADERS2;
        } else {
          return response.text();
        }
      }
    );
  }
  queryJson() {
    this.format(JSON_FORMAT2);
    const url2 = this.formURL(TAUP_TIME_TOOL);
    const fetchInit = defaultFetchInitObj(JSON_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
        return createEmptyTraveltimeJson2(this);
      } else {
        return response.json();
      }
    }).then((jsonValue) => {
      if (isValidTauP3TimeJsonType(jsonValue)) {
        return jsonValue;
      } else {
        throw new TypeError(`Oops, we did not get root traveltime JSON! ${JSON.stringify(jsonValue)}`);
      }
    });
  }
  querySvg() {
    this.format(SVG_FORMAT2);
    const url2 = this.formURL(TAUP_PATH_TOOL);
    const fetchInit = defaultFetchInitObj(SVG_MIME);
    return doFetchWithTimeout(url2, fetchInit, this._timeoutSec * 1e3).then((response) => {
      if (response.status === 200) {
        return response.text();
      } else if (response.status === 204 || isDef(this._nodata) && response.status === this._nodata) {
        return FAKE_EMPTY_SVG2;
      } else {
        throw new Error(`Status not successful: ${response.status}`);
      }
    }).then(function(rawXmlText) {
      return new DOMParser().parseFromString(rawXmlText, SVG_MIME);
    }).then((xml) => {
      const elArray = xml.getElementsByTagName("svg");
      if (elArray.length > 0) {
        return elArray[0];
      } else {
        throw new Error("Can't find svg element in response");
      }
    });
  }
  query() {
    if (this._format === JSON_FORMAT2) {
      return this.queryJson();
    } else if (this._format === SVG_FORMAT2) {
      return this.querySvg();
    } else if (this._format === TEXT_FORMAT2) {
      return this.queryText();
    } else {
      throw new Error("Unknown format: " + this._format);
    }
  }
  /**
   * Forms the basic URL to contact the web service, without any query paramters
   *
   * @returns the url
   */
  formBaseURL() {
    let colon = ":";
    if (this._protocol.endsWith(colon)) {
      colon = "";
    }
    const port = this.defaultPortStringForProtocol(this._protocol);
    const path2 = `${this._path_base}/${this._service}/${this._specVersion}`;
    return `${this._protocol}${colon}//${this._host}${port}/${path2}`;
  }
  formURL(toolname) {
    if (toolname == null) {
      toolname = TAUP_TIME_TOOL;
    }
    let url2 = appendToPath(this.formBaseURL(), `${toolname}?`);
    if (isDef(this._noheader) && this._noheader) {
      url2 = url2 + "noheader=true&";
    }
    if (isDef(this._evdepth) && this._evdepth.length !== 0) {
      url2 = url2 + makeParam("evdepth", this._evdepth.join(","));
    }
    if (isDef(this._receiverdepth) && this._receiverdepth.length !== 0) {
      url2 = url2 + makeParam("receiverdepth", this._receiverdepth.join(","));
    }
    if (isDef(this._stalat) && isDef(this._stalon)) {
      url2 = url2 + makeParam(
        "station",
        stringify(this._stalat) + "," + stringify(this._stalon)
      );
    }
    if (isDef(this._evlat) && isDef(this._evlon)) {
      url2 = url2 + makeParam(
        "event",
        stringify(this._evlat) + "," + stringify(this._evlon)
      );
    }
    if (isDef(this._distdeg) && this._distdeg.length !== 0) {
      url2 = url2 + makeParam("deg", this._distdeg.join(","));
    }
    if (isDef(this._model)) {
      url2 = url2 + makeParam("model", this._model);
    }
    if (isDef(this._phases)) {
      url2 = url2 + makeParam("phase", this._phases);
    }
    if (isDef(this._format)) {
      url2 = url2 + makeParam("format", this._format);
    }
    if (isDef(this._nodata)) {
      url2 = url2 + makeParam("nodata", this._nodata);
    }
    if (url2.endsWith("&") || url2.endsWith("?")) {
      url2 = url2.substr(0, url2.length - 1);
    }
    return url2;
  }
  queryTauPVersion() {
    return fetch(this.formTauPVersionURL()).then((response) => {
      if (response.ok) {
        return response.text();
      } else {
        throw new Error(
          "Fetching over network was not ok: " + response.status + " " + response.statusText
        );
      }
    });
  }
  formTauPVersionURL() {
    return appendToPath(this.formBaseURL(), "version");
  }
};
var FAKE_EMPTY_TEXT_MODEL2 = `Model: `;
var FAKE_EMPTY_TEXT_HEADERS2 = `
Distance   Depth   Phase   Travel    Ray Param  Takeoff  Incident  Purist    Purist
  (deg)     (km)   Name    Time (s)  p (s/deg)   (deg)    (deg)   Distance   Name
-----------------------------------------------------------------------------------
`;
function createEmptyTraveltimeJson2(ttquery) {
  const out = {
    model: isDef(ttquery._model) ? ttquery._model : "",
    sourcedepthlist: isDef(ttquery._evdepth) ? ttquery._evdepth : [0],
    receiverdepthlist: isDef(ttquery._receiverdepth) ? ttquery._receiverdepth : [0],
    phases: isDef(ttquery._phases) ? ttquery._phases.split(",") : [],
    arrivals: []
  };
  return out;
}
var FAKE_EMPTY_SVG2 = `
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg" width="500" height="500" viewBox="0 0 14016.2 14016.2">
<!--
 This script will plot ray paths generated by TauP using SVG. -->
<defs>
    <style type="text/css"><![CDATA[
        circle {
            vector-effect: non-scaling-stroke;
            stroke: grey;
            fill: none;
        }
        polyline {
            vector-effect: non-scaling-stroke;
            stroke: black;
            fill: none;
        }
    ]]></style>
</defs>
<g transform="translate(7008.1,7008.1)" >
<!-- draw surface and label distances.-->
<!-- tick marks every 30 degrees.-->
  <polyline points="    0.00  -6371.00,     0.00  -6689.55" />
  <polyline points=" 3185.50  -5517.45,  3344.78  -5793.32" />
  <polyline points=" 5517.45  -3185.50,  5793.32  -3344.77" />
  <polyline points=" 6371.00      0.00,  6689.55      0.00" />
  <polyline points=" 5517.45   3185.50,  5793.32   3344.77" />
  <polyline points=" 3185.50   5517.45,  3344.78   5793.32" />
  <polyline points="    0.00   6371.00,     0.00   6689.55" />
  <polyline points="-3185.50   5517.45, -3344.77   5793.32" />
  <polyline points="-5517.45   3185.50, -5793.32   3344.77" />
  <polyline points="-6371.00      0.00, -6689.55      0.00" />
  <polyline points="-5517.45  -3185.50, -5793.32  -3344.78" />
  <polyline points="-3185.50  -5517.45, -3344.78  -5793.32" />
  <circle cx="0.0" cy="0.0" r="6371.0" />
  </g>
</svg>
`;

// src/transfer.mts
var transfer_exports = {};
__export(transfer_exports, {
  METER: () => METER,
  METER_PER_SECOND: () => METER_PER_SECOND,
  METER_PER_SECOND_PER_SECOND: () => METER_PER_SECOND_PER_SECOND,
  applyFreqTaper: () => applyFreqTaper,
  calcFreqTaper: () => calcFreqTaper,
  calcGamma: () => calcGamma,
  calcResponse: () => calcResponse,
  calcResponseFromSacPoleZero: () => calcResponseFromSacPoleZero,
  calcScaleUnit: () => calcScaleUnit,
  calc_A0: () => calc_A0,
  combine: () => combine,
  convertPoleZeroToSacStyle: () => convertPoleZeroToSacStyle,
  convertToSacPoleZero: () => convertToSacPoleZero,
  evalPoleZeroInverse: () => evalPoleZeroInverse,
  transfer: () => transfer,
  transferSacPZ: () => transferSacPZ,
  transferSacPZSegment: () => transferSacPZSegment
});

// node_modules/convert-units/lib/esm/wrapper.js
function isWrapper(wrapper) {
  return wrapper != null && typeof wrapper === "object" && "create" in wrapper && typeof wrapper.create === "function" && "add" in wrapper && typeof wrapper.add === "function" && "sub" in wrapper && typeof wrapper.sub === "function" && "mul" in wrapper && typeof wrapper.mul === "function" && "div" in wrapper && typeof wrapper.div === "function" && "lt" in wrapper && typeof wrapper.lt === "function" && "lte" in wrapper && typeof wrapper.lte === "function" && "gt" in wrapper && typeof wrapper.gt === "function" && "gte" in wrapper && typeof wrapper.gte === "function";
}
var NotAValidNumber = class extends Error {
};

// node_modules/convert-units/lib/esm/number_wrapper.js
var DefaultWrapper = {
  create(value) {
    const result = Number(value);
    if (Number.isNaN(result)) {
      throw new NotAValidNumber(`"${value}" cannot be parsed into a number`);
    }
    return result;
  },
  add(left2, right2) {
    return Number(left2) + Number(right2);
  },
  sub(left2, right2) {
    return Number(left2) - Number(right2);
  },
  mul(left2, right2) {
    return Number(left2) * Number(right2);
  },
  div(left2, right2) {
    return Number(left2) / Number(right2);
  },
  lt(left2, right2) {
    return Number(left2) < Number(right2);
  },
  lte(left2, right2) {
    return Number(left2) <= Number(right2);
  },
  gt(left2, right2) {
    return Number(left2) > Number(right2);
  },
  gte(left2, right2) {
    return Number(left2) >= Number(right2);
  }
};
var number_wrapper_default = DefaultWrapper;

// node_modules/convert-units/lib/esm/convert.js
function isFraction(value) {
  return value != null && typeof value === "object" && "numerator" in value && (typeof value.numerator === "number" || typeof value.numerator === "string") && "denominator" in value && (typeof value.denominator === "number" || typeof value.denominator === "string");
}
var UnknownUnitError = class extends Error {
};
var OperationOrderError = class extends Error {
};
var IncompatibleUnitError = class extends Error {
};
var MeasureStructureError = class extends Error {
};
var UnknownMeasureError = class extends Error {
};
var Converter = class {
  constructor(options, value) {
    this.destination = null;
    this.origin = null;
    this.cls = options.cls;
    this.val = this.cls.create(value ? value : 0);
    this.measureData = options.measures;
    this.unitCache = options.unitCache;
  }
  /**
   * Lets the converter know the source unit abbreviation
   *
   * @throws OperationOrderError, UnknownUnitError
   */
  from(from) {
    if (this.destination != null)
      throw new OperationOrderError(".from must be called before .to");
    this.origin = this.getUnit(from);
    if (this.origin == null) {
      this.throwUnsupportedUnitError(from);
    }
    return this;
  }
  convertFraction(value) {
    if (isFraction(value)) {
      return this.cls.div(value.numerator, value.denominator);
    }
    return this.cls.create(value);
  }
  /**
   * Converts the unit and returns the value
   *
   * @throws OperationOrderError, UnknownUnitError, IncompatibleUnitError, MeasureStructureError
   */
  to(to) {
    var _a3, _b;
    if (this.origin == null)
      throw new Error(".to must be called after .from");
    this.destination = this.getUnit(to);
    if (this.destination == null) {
      this.throwUnsupportedUnitError(to);
    }
    const destination = this.destination;
    const origin = this.origin;
    if (origin.abbr === destination.abbr) {
      return this.val;
    }
    if (destination.measure != origin.measure) {
      throw new IncompatibleUnitError(`Cannot convert incompatible measures of ${destination.measure} and ${origin.measure}`);
    }
    let result = this.cls.mul(this.val, this.convertFraction(origin.unit.to_anchor));
    if (origin.unit.anchor_shift) {
      result = this.cls.sub(result, this.convertFraction(origin.unit.anchor_shift));
    }
    if (origin.system != destination.system) {
      const measure30 = this.measureData[origin.measure];
      const anchors = measure30.anchors;
      if (anchors == null) {
        throw new MeasureStructureError(`Unable to convert units. Anchors are missing for "${origin.measure}" and "${destination.measure}" measures.`);
      }
      const anchor = anchors[origin.system];
      if (anchor == null) {
        throw new MeasureStructureError(`Unable to find anchor for "${origin.measure}" to "${destination.measure}". Please make sure it is defined.`);
      }
      const transform2 = (_a3 = anchor[destination.system]) === null || _a3 === void 0 ? void 0 : _a3.transform;
      const ratio = (_b = anchor[destination.system]) === null || _b === void 0 ? void 0 : _b.ratio;
      if (typeof transform2 === "function") {
        result = transform2(result, this.cls);
      } else if (typeof ratio === "number") {
        result = this.cls.mul(result, ratio);
      } else if (isFraction(ratio)) {
        result = this.cls.mul(result, this.convertFraction(ratio));
      } else {
        throw new MeasureStructureError("A system anchor needs to either have a defined ratio number or a transform function.");
      }
    }
    if (destination.unit.anchor_shift) {
      result = this.cls.add(result, this.convertFraction(destination.unit.anchor_shift));
    }
    return this.cls.div(result, this.convertFraction(destination.unit.to_anchor));
  }
  /**
   * Converts the unit to the best available unit.
   *
   * @throws OperationOrderError
   */
  toBest(options) {
    var _a3, _b, _c;
    if (this.origin == null)
      throw new OperationOrderError(".toBest must be called after .from");
    const isNegative = this.cls.lt(this.val, 0);
    let exclude = [];
    let cutOffNumber = isNegative ? -1 : 1;
    let system = this.origin.system;
    if (typeof options === "object") {
      exclude = (_a3 = options.exclude) !== null && _a3 !== void 0 ? _a3 : [];
      cutOffNumber = (_b = options.cutOffNumber) !== null && _b !== void 0 ? _b : cutOffNumber;
      system = (_c = options.system) !== null && _c !== void 0 ? _c : this.origin.system;
    }
    let best = null;
    for (const possibility of this.possibilities()) {
      const unit3 = this.describe(possibility);
      const isIncluded = exclude.indexOf(possibility) === -1;
      if (isIncluded && unit3.system === system) {
        const result = this.to(possibility);
        if (isNegative ? this.cls.gt(result, cutOffNumber) : this.cls.lt(result, cutOffNumber)) {
          continue;
        }
        if (best === null || (isNegative ? this.cls.lte(result, cutOffNumber) && this.cls.gt(result, best.val) : this.cls.gte(result, cutOffNumber) && this.cls.lt(result, best.val))) {
          best = {
            val: result,
            unit: possibility,
            singular: unit3.singular,
            plural: unit3.plural
          };
        }
      }
    }
    if (best == null) {
      return {
        val: this.val,
        unit: this.origin.abbr,
        singular: this.origin.unit.name.singular,
        plural: this.origin.unit.name.plural
      };
    }
    return best;
  }
  /**
   * Finds the unit
   */
  getUnit(abbr) {
    var _a3;
    return (_a3 = this.unitCache.get(abbr)) !== null && _a3 !== void 0 ? _a3 : null;
  }
  /**
   * Provides additional information about the unit
   *
   * @throws UnknownUnitError
   */
  describe(abbr) {
    const result = this.getUnit(abbr);
    if (result != null) {
      return this.describeUnit(result);
    }
    this.throwUnsupportedUnitError(abbr);
  }
  describeUnit(unit3) {
    return {
      abbr: unit3.abbr,
      measure: unit3.measure,
      system: unit3.system,
      singular: unit3.unit.name.singular,
      plural: unit3.unit.name.plural
    };
  }
  /**
   * Detailed list of all supported units
   *
   * If a measure is supplied the list will only contain
   * details about that measure. Otherwise the list will contain
   * details abaout all measures.
   *
   * However, if the measure doesn't exist, an empty array will be
   * returned
   *
   *
   */
  list(measureName) {
    const list = [];
    if (measureName == null) {
      for (const [name, measure30] of Object.entries(this.measureData)) {
        for (const [systemName, units] of Object.entries(measure30.systems)) {
          for (const [abbr, unit3] of Object.entries(units)) {
            list.push(this.describeUnit({
              abbr,
              measure: name,
              system: systemName,
              unit: unit3
            }));
          }
        }
      }
    } else {
      if (!this.isMeasure(measureName))
        throw new UnknownMeasureError(`Meausure "${measureName}" not found.`);
      const measure30 = this.measureData[measureName];
      for (const [systemName, units] of Object.entries(measure30.systems)) {
        for (const [abbr, unit3] of Object.entries(units)) {
          list.push(this.describeUnit({
            abbr,
            measure: measureName,
            system: systemName,
            unit: unit3
          }));
        }
      }
    }
    return list;
  }
  isMeasure(measureName) {
    return measureName in this.measureData;
  }
  throwUnsupportedUnitError(what) {
    let validUnits = [];
    for (const measure30 of Object.values(this.measureData)) {
      for (const systems of Object.values(measure30.systems)) {
        validUnits = validUnits.concat(Object.keys(systems));
      }
    }
    throw new UnknownUnitError(`Unsupported unit ${what}, use one of: ${validUnits.join(", ")}`);
  }
  /**
   * Returns the abbreviated measures that the value can be
   * converted to.
   */
  possibilities(forMeasure) {
    let possibilities = [];
    let list_measures = [];
    if (typeof forMeasure == "string" && this.isMeasure(forMeasure)) {
      list_measures.push(forMeasure);
    } else if (this.origin != null) {
      list_measures.push(this.origin.measure);
    } else {
      list_measures = Object.keys(this.measureData);
    }
    for (const measure30 of list_measures) {
      const systems = this.measureData[measure30].systems;
      for (const system of Object.values(systems)) {
        possibilities = [
          ...possibilities,
          ...Object.keys(system)
        ];
      }
    }
    return possibilities;
  }
  /**
   * Returns the abbreviated measures that the value can be
   * converted to.
   */
  measures() {
    return Object.keys(this.measureData);
  }
};
function buildUnitCache(measures) {
  const unitCache = /* @__PURE__ */ new Map();
  for (const [measureName, measure30] of Object.entries(measures)) {
    for (const [systemName, system] of Object.entries(measure30.systems)) {
      for (const [testAbbr, unit3] of Object.entries(system)) {
        unitCache.set(testAbbr, {
          measure: measureName,
          system: systemName,
          abbr: testAbbr,
          unit: unit3
        });
      }
    }
  }
  return unitCache;
}
function configureMeasurements(measures, cls) {
  if (typeof measures !== "object") {
    throw new TypeError("The measures argument needs to be an object");
  }
  const unitCache = buildUnitCache(measures);
  if (cls != null && isWrapper(cls)) {
    return (value) => new Converter({
      measures,
      unitCache,
      cls
    }, value);
  } else {
    return (value) => new Converter({
      measures,
      unitCache,
      cls: number_wrapper_default
    }, value);
  }
}

// node_modules/convert-units/lib/esm/definitions/acceleration.js
var metric = {
  "g-force": {
    name: {
      singular: "g-force",
      plural: "g-forces"
    },
    to_anchor: 9.80665
  },
  "m/s2": {
    name: {
      singular: "Metre per second squared",
      plural: "Metres per second squared"
    },
    to_anchor: 1
  },
  g0: {
    name: {
      singular: "Standard Gravity",
      plural: "Standard Gravities"
    },
    to_anchor: 9.80665
  }
};
var measure = {
  systems: {
    metric
  }
};
var acceleration_default = measure;

// node_modules/convert-units/lib/esm/definitions/angle.js
var SI = {
  rad: {
    name: {
      singular: "radian",
      plural: "radians"
    },
    to_anchor: {
      numerator: 180,
      denominator: Math.PI
    }
  },
  deg: {
    name: {
      singular: "degree",
      plural: "degrees"
    },
    to_anchor: 1
  },
  grad: {
    name: {
      singular: "gradian",
      plural: "gradians"
    },
    to_anchor: {
      numerator: 9,
      denominator: 10
    }
  },
  arcmin: {
    name: {
      singular: "arcminute",
      plural: "arcminutes"
    },
    to_anchor: {
      numerator: 1,
      denominator: 60
    }
  },
  arcsec: {
    name: {
      singular: "arcsecond",
      plural: "arcseconds"
    },
    to_anchor: {
      numerator: 1,
      denominator: 3600
    }
  }
};
var measure2 = {
  systems: {
    SI
  }
};
var angle_default = measure2;

// node_modules/convert-units/lib/esm/definitions/apparentPower.js
var SI2 = {
  VA: {
    name: {
      singular: "Volt-Ampere",
      plural: "Volt-Amperes"
    },
    to_anchor: 1
  },
  mVA: {
    name: {
      singular: "Millivolt-Ampere",
      plural: "Millivolt-Amperes"
    },
    to_anchor: 1e-3
  },
  kVA: {
    name: {
      singular: "Kilovolt-Ampere",
      plural: "Kilovolt-Amperes"
    },
    to_anchor: 1e3
  },
  MVA: {
    name: {
      singular: "Megavolt-Ampere",
      plural: "Megavolt-Amperes"
    },
    to_anchor: 1e6
  },
  GVA: {
    name: {
      singular: "Gigavolt-Ampere",
      plural: "Gigavolt-Amperes"
    },
    to_anchor: 1e9
  }
};
var measure3 = {
  systems: {
    SI: SI2
  }
};
var apparentPower_default = measure3;

// node_modules/convert-units/lib/esm/definitions/area.js
var metric2 = {
  nm2: {
    name: {
      singular: "Square Nanometer",
      plural: "Square Nanometers"
    },
    to_anchor: 1e-18
  },
  \u03BCm2: {
    name: {
      singular: "Square Micrometer",
      plural: "Square Micrometers"
    },
    to_anchor: 1e-12
  },
  mm2: {
    name: {
      singular: "Square Millimeter",
      plural: "Square Millimeters"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e6
    }
  },
  cm2: {
    name: {
      singular: "Square Centimeter",
      plural: "Square Centimeters"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e4
    }
  },
  dm2: {
    name: {
      singular: "Square Decimeter",
      plural: "Square Decimeters"
    },
    to_anchor: {
      numerator: 1,
      denominator: 100
    }
  },
  m2: {
    name: {
      singular: "Square Meter",
      plural: "Square Meters"
    },
    to_anchor: 1
  },
  a: {
    name: {
      singular: "Are",
      plural: "Ares"
    },
    to_anchor: 100
  },
  ha: {
    name: {
      singular: "Hectare",
      plural: "Hectares"
    },
    to_anchor: 1e4
  },
  km2: {
    name: {
      singular: "Square Kilometer",
      plural: "Square Kilometers"
    },
    to_anchor: 1e6
  }
};
var imperial = {
  in2: {
    name: {
      singular: "Square Inch",
      plural: "Square Inches"
    },
    to_anchor: {
      numerator: 1,
      denominator: 144
    }
  },
  yd2: {
    name: {
      singular: "Square Yard",
      plural: "Square Yards"
    },
    to_anchor: 9
  },
  ft2: {
    name: {
      singular: "Square Foot",
      plural: "Square Feet"
    },
    to_anchor: 1
  },
  ac: {
    name: {
      singular: "Acre",
      plural: "Acres"
    },
    to_anchor: 43560
  },
  mi2: {
    name: {
      singular: "Square Mile",
      plural: "Square Miles"
    },
    to_anchor: 27878400
  }
};
var measure4 = {
  systems: {
    metric: metric2,
    imperial
  },
  anchors: {
    metric: {
      imperial: {
        ratio: 10.7639
      }
    },
    imperial: {
      metric: {
        ratio: {
          numerator: 1,
          denominator: 10.7639
        }
      }
    }
  }
};
var area_default = measure4;

// node_modules/convert-units/lib/esm/definitions/charge.js
var SI3 = {
  c: {
    name: {
      singular: "Coulomb",
      plural: "Coulombs"
    },
    to_anchor: 1
  },
  mC: {
    name: {
      singular: "Millicoulomb",
      plural: "Millicoulombs"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e3
    }
  },
  \u03BCC: {
    name: {
      singular: "Microcoulomb",
      plural: "Microcoulombs"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e6
    }
  },
  nC: {
    name: {
      singular: "Nanocoulomb",
      plural: "Nanocoulombs"
    },
    to_anchor: 1e-9
  },
  pC: {
    name: {
      singular: "Picocoulomb",
      plural: "Picocoulombs"
    },
    to_anchor: 1e-12
  }
};
var measure5 = {
  systems: {
    SI: SI3
  }
};
var charge_default = measure5;

// node_modules/convert-units/lib/esm/definitions/current.js
var SI4 = {
  A: {
    name: {
      singular: "Ampere",
      plural: "Amperes"
    },
    to_anchor: 1
  },
  \u03BCA: {
    name: {
      singular: "Microampere",
      plural: "Microamperes"
    },
    to_anchor: 1e-6
  },
  mA: {
    name: {
      singular: "Milliampere",
      plural: "Milliamperes"
    },
    to_anchor: 1e-3
  },
  kA: {
    name: {
      singular: "Kiloampere",
      plural: "Kiloamperes"
    },
    to_anchor: 1e3
  },
  MA: {
    name: {
      singular: "Megaampere",
      plural: "Megaamperes"
    },
    to_anchor: 1e6
  }
};
var measure6 = {
  systems: {
    SI: SI4
  }
};
var current_default = measure6;

// node_modules/convert-units/lib/esm/definitions/digital.js
var bit = {
  bit: {
    name: {
      singular: "Bit",
      plural: "Bits"
    },
    to_anchor: 1
  },
  kb: {
    name: {
      singular: "Kilobit",
      plural: "Kilobits"
    },
    to_anchor: 1e3
  },
  Mb: {
    name: {
      singular: "Megabit",
      plural: "Megabits"
    },
    to_anchor: 1e6
  },
  Gb: {
    name: {
      singular: "Gigabit",
      plural: "Gigabits"
    },
    to_anchor: 1e9
  },
  Tb: {
    name: {
      singular: "Terabit",
      plural: "Terabits"
    },
    to_anchor: 1e12
  }
};
var byte = {
  byte: {
    name: {
      singular: "Byte",
      plural: "Bytes"
    },
    to_anchor: 1
  },
  kB: {
    name: {
      singular: "Kilobyte",
      plural: "Kilobytes"
    },
    to_anchor: 1e3
  },
  MB: {
    name: {
      singular: "Megabyte",
      plural: "Megabytes"
    },
    to_anchor: 1e6
  },
  GB: {
    name: {
      singular: "Gigabyte",
      plural: "Gigabytes"
    },
    to_anchor: 1e9
  },
  TB: {
    name: {
      singular: "Terabyte",
      plural: "Terabytes"
    },
    to_anchor: 1e12
  }
};
var IECBit = {
  Kib: {
    name: {
      singular: "Kibibit",
      plural: "Kibibits"
    },
    to_anchor: 1
  },
  Mib: {
    name: {
      singular: "Mebibit",
      plural: "Mebibits"
    },
    to_anchor: 1024
  },
  Gib: {
    name: {
      singular: "Gibibit",
      plural: "Gibibits"
    },
    to_anchor: 1048576
  },
  Tib: {
    name: {
      singular: "Tebibit",
      plural: "Tebibits"
    },
    to_anchor: 1073741824
  }
};
var IECByte = {
  KiB: {
    name: {
      singular: "Kibibyte",
      plural: "Kibibytes"
    },
    to_anchor: 1
  },
  MiB: {
    name: {
      singular: "Mebibyte",
      plural: "Mebibytes"
    },
    to_anchor: 1024
  },
  GiB: {
    name: {
      singular: "Gibibyte",
      plural: "Gibibytes"
    },
    to_anchor: 1048576
  },
  TiB: {
    name: {
      singular: "Tebibyte",
      plural: "Tebibytes"
    },
    to_anchor: 1073741824
  }
};
var measure7 = {
  systems: {
    bit,
    byte,
    IECBit,
    IECByte
  },
  anchors: {
    bit: {
      byte: {
        ratio: 0.125
      },
      IECBit: {
        ratio: 9765625e-10
      },
      IECByte: {
        ratio: 1220703125e-13
      }
    },
    byte: {
      bit: {
        ratio: 8
      },
      IECBit: {
        ratio: 78125e-7
      },
      IECByte: {
        ratio: 9765625e-10
      }
    },
    IECBit: {
      bit: {
        ratio: 1024
      },
      byte: {
        ratio: 128
      },
      IECByte: {
        ratio: 0.125
      }
    },
    IECByte: {
      bit: {
        ratio: 8192
      },
      byte: {
        ratio: 1024
      },
      IECBit: {
        ratio: 8
      }
    }
  }
};
var digital_default = measure7;

// node_modules/convert-units/lib/esm/definitions/each.js
var metric3 = {
  ea: {
    name: {
      singular: "Each",
      plural: "Each"
    },
    to_anchor: 1
  },
  dz: {
    name: {
      singular: "Dozen",
      plural: "Dozens"
    },
    to_anchor: 12
  }
};
var measure8 = {
  systems: {
    metric: metric3
  }
};
var each_default2 = measure8;

// node_modules/convert-units/lib/esm/definitions/energy.js
var SI5 = {
  Ws: {
    name: {
      singular: "Watt-second",
      plural: "Watt-seconds"
    },
    to_anchor: 1
  },
  Wm: {
    name: {
      singular: "Watt-minute",
      plural: "Watt-minutes"
    },
    to_anchor: 60
  },
  Wh: {
    name: {
      singular: "Watt-hour",
      plural: "Watt-hours"
    },
    to_anchor: 3600
  },
  mWh: {
    name: {
      singular: "Milliwatt-hour",
      plural: "Milliwatt-hours"
    },
    to_anchor: 3.6
  },
  kWh: {
    name: {
      singular: "Kilowatt-hour",
      plural: "Kilowatt-hours"
    },
    to_anchor: 36e5
  },
  MWh: {
    name: {
      singular: "Megawatt-hour",
      plural: "Megawatt-hours"
    },
    to_anchor: 36e8
  },
  GWh: {
    name: {
      singular: "Gigawatt-hour",
      plural: "Gigawatt-hours"
    },
    to_anchor: 36e11
  },
  J: {
    name: {
      singular: "Joule",
      plural: "Joules"
    },
    to_anchor: 1
  },
  kJ: {
    name: {
      singular: "Kilojoule",
      plural: "Kilojoules"
    },
    to_anchor: 1e3
  },
  MJ: {
    name: {
      singular: "Megajoule",
      plural: "Megajoules"
    },
    to_anchor: 1e6
  },
  GJ: {
    name: {
      singular: "Gigajoule",
      plural: "Gigajoules"
    },
    to_anchor: 1e9
  }
};
var nutrition = {
  cal: {
    name: {
      singular: "calorie",
      plural: "calories"
    },
    to_anchor: 1
  },
  kcal: {
    name: {
      singular: "Kilocalorie",
      plural: "Kilocalories"
    },
    to_anchor: 1e3
  }
};
var measure9 = {
  systems: {
    SI: SI5,
    nutrition
  },
  anchors: {
    SI: {
      nutrition: {
        ratio: {
          numerator: 1,
          denominator: 4.184
        }
      }
    },
    nutrition: {
      SI: {
        ratio: 4.184
      }
    }
  }
};
var energy_default = measure9;

// node_modules/convert-units/lib/esm/definitions/force.js
var SI6 = {
  N: {
    name: {
      singular: "Newton",
      plural: "Newtons"
    },
    to_anchor: 1
  },
  kN: {
    name: {
      singular: "Kilonewton",
      plural: "Kilonewtons"
    },
    to_anchor: 1e3
  },
  lbf: {
    name: {
      singular: "Pound-force",
      plural: "Pound-forces"
    },
    to_anchor: 4.44822
  },
  kgf: {
    name: {
      singular: "Kilogram-force",
      plural: "Kilogram-forces"
    },
    to_anchor: 9.807
  }
};
var measure10 = {
  systems: {
    SI: SI6
  }
};
var force_default = measure10;

// node_modules/convert-units/lib/esm/definitions/frequency.js
var SI7 = {
  mHz: {
    name: {
      singular: "millihertz",
      plural: "millihertz"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e3
    }
  },
  Hz: {
    name: {
      singular: "hertz",
      plural: "hertz"
    },
    to_anchor: 1
  },
  kHz: {
    name: {
      singular: "kilohertz",
      plural: "kilohertz"
    },
    to_anchor: 1e3
  },
  MHz: {
    name: {
      singular: "megahertz",
      plural: "megahertz"
    },
    to_anchor: 1e6
  },
  GHz: {
    name: {
      singular: "gigahertz",
      plural: "gigahertz"
    },
    to_anchor: 1e9
  },
  THz: {
    name: {
      singular: "terahertz",
      plural: "terahertz"
    },
    to_anchor: 1e12
  },
  rpm: {
    name: {
      singular: "rotation per minute",
      plural: "rotations per minute"
    },
    to_anchor: {
      numerator: 1,
      denominator: 60
    }
  },
  "deg/s": {
    name: {
      singular: "degree per second",
      plural: "degrees per second"
    },
    to_anchor: {
      numerator: 1,
      denominator: 360
    }
  },
  "rad/s": {
    name: {
      singular: "radian per second",
      plural: "radians per second"
    },
    to_anchor: {
      numerator: 1,
      denominator: 6.283185307179586
      // Math.PI * 2
    }
  }
};
var measure11 = {
  systems: {
    SI: SI7
  }
};
var frequency_default = measure11;

// node_modules/convert-units/lib/esm/definitions/illuminance.js
var metric4 = {
  lx: {
    name: {
      singular: "Lux",
      plural: "Lux"
    },
    to_anchor: 1
  }
};
var imperial2 = {
  "ft-cd": {
    name: {
      singular: "Foot-candle",
      plural: "Foot-candles"
    },
    to_anchor: 1
  }
};
var measure12 = {
  systems: {
    metric: metric4,
    imperial: imperial2
  },
  anchors: {
    metric: {
      imperial: {
        ratio: {
          numerator: 1,
          denominator: 10.76391
        }
      }
    },
    imperial: {
      metric: {
        ratio: 10.76391
      }
    }
  }
};
var illuminance_default = measure12;

// node_modules/convert-units/lib/esm/definitions/length.js
var metric5 = {
  nm: {
    name: {
      singular: "Nanometer",
      plural: "Nanometers"
    },
    to_anchor: 1e-9
  },
  \u03BCm: {
    name: {
      singular: "Micrometer",
      plural: "Micrometers"
    },
    to_anchor: 1e-6
  },
  mm: {
    name: {
      singular: "Millimeter",
      plural: "Millimeters"
    },
    to_anchor: 1e-3
  },
  cm: {
    name: {
      singular: "Centimeter",
      plural: "Centimeters"
    },
    to_anchor: 0.01
  },
  dm: {
    name: {
      singular: "Decimeter",
      plural: "Decimeters"
    },
    to_anchor: 0.1
  },
  m: {
    name: {
      singular: "Meter",
      plural: "Meters"
    },
    to_anchor: 1
  },
  km: {
    name: {
      singular: "Kilometer",
      plural: "Kilometers"
    },
    to_anchor: 1e3
  }
};
var imperial3 = {
  mil: {
    name: {
      singular: "Mil",
      plural: "Mils"
    },
    to_anchor: {
      numerator: 1,
      denominator: 12e3
    }
  },
  in: {
    name: {
      singular: "Inch",
      plural: "Inches"
    },
    to_anchor: {
      numerator: 1,
      denominator: 12
    }
  },
  yd: {
    name: {
      singular: "Yard",
      plural: "Yards"
    },
    to_anchor: 3
  },
  "ft-us": {
    name: {
      singular: "US Survey Foot",
      plural: "US Survey Feet"
    },
    to_anchor: 1.000002
  },
  ft: {
    name: {
      singular: "Foot",
      plural: "Feet"
    },
    to_anchor: 1
  },
  fathom: {
    name: {
      singular: "Fathom",
      plural: "Fathoms"
    },
    to_anchor: 6
  },
  mi: {
    name: {
      singular: "Mile",
      plural: "Miles"
    },
    to_anchor: 5280
  },
  nMi: {
    name: {
      singular: "Nautical Mile",
      plural: "Nautical Miles"
    },
    to_anchor: 6076.12
  }
};
var measure13 = {
  systems: {
    metric: metric5,
    imperial: imperial3
  },
  anchors: {
    metric: {
      imperial: {
        ratio: 3.28084
      }
    },
    imperial: {
      metric: {
        ratio: {
          numerator: 1,
          denominator: 3.28084
        }
      }
    }
  }
};
var length_default = measure13;

// node_modules/convert-units/lib/esm/definitions/mass.js
var metric6 = {
  mcg: {
    name: {
      singular: "Microgram",
      plural: "Micrograms"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e6
    }
  },
  mg: {
    name: {
      singular: "Milligram",
      plural: "Milligrams"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e3
    }
  },
  g: {
    name: {
      singular: "Gram",
      plural: "Grams"
    },
    to_anchor: 1
  },
  kg: {
    name: {
      singular: "Kilogram",
      plural: "Kilograms"
    },
    to_anchor: 1e3
  },
  mt: {
    name: {
      singular: "Metric Tonne",
      plural: "Metric Tonnes"
    },
    to_anchor: 1e6
  }
};
var imperial4 = {
  oz: {
    name: {
      singular: "Ounce",
      plural: "Ounces"
    },
    to_anchor: {
      numerator: 1,
      denominator: 16
    }
  },
  lb: {
    name: {
      singular: "Pound",
      plural: "Pounds"
    },
    to_anchor: 1
  },
  st: {
    name: {
      singular: "Stone",
      plural: "Stones"
    },
    to_anchor: 14
  },
  t: {
    name: {
      singular: "Ton",
      plural: "Tons"
    },
    to_anchor: 2e3
  }
};
var measure14 = {
  systems: {
    metric: metric6,
    imperial: imperial4
  },
  anchors: {
    metric: {
      imperial: {
        ratio: {
          numerator: 1,
          denominator: 453.59237
        }
      }
    },
    imperial: {
      metric: {
        ratio: 453.59237
      }
    }
  }
};
var mass_default = measure14;

// node_modules/convert-units/lib/esm/definitions/massFlowRate.js
var metric7 = {
  "kg/s": {
    name: {
      singular: "Kilogram per second",
      plural: "Kilograms per second"
    },
    to_anchor: 1
  },
  "kg/min": {
    name: {
      singular: "Kilogram per minute",
      plural: "Kilograms per minute"
    },
    to_anchor: 1 / 60
  },
  "kg/h": {
    name: {
      singular: "Kilogram per hour",
      plural: "Kilograms per hour"
    },
    to_anchor: {
      numerator: 1,
      denominator: 3600
    }
  },
  "mt/h": {
    name: {
      singular: "Ton per hour",
      plural: "Tons per hour"
    },
    to_anchor: {
      numerator: 1,
      denominator: 3.6
    }
  }
};
var imperial5 = {
  "lb/s": {
    name: {
      singular: "Pound per second",
      plural: "Pounds per second"
    },
    to_anchor: 1
  },
  "lb/h": {
    name: {
      singular: "Pound per hour",
      plural: "Pounds per hour"
    },
    to_anchor: {
      numerator: 1,
      denominator: 3600
    }
  }
};
var measure15 = {
  systems: {
    metric: metric7,
    imperial: imperial5
  },
  anchors: {
    metric: {
      imperial: {
        ratio: {
          numerator: 1,
          denominator: 0.453592
        }
      }
    },
    imperial: {
      metric: {
        ratio: 0.453592
      }
    }
  }
};
var massFlowRate_default = measure15;

// node_modules/convert-units/lib/esm/definitions/pace.js
var metric8 = {
  "min/km": {
    name: {
      singular: "Minute per kilometre",
      plural: "Minutes per kilometre"
    },
    to_anchor: 0.06
  },
  "s/m": {
    name: {
      singular: "Second per metre",
      plural: "Seconds per metre"
    },
    to_anchor: 1
  }
};
var imperial6 = {
  "min/mi": {
    name: {
      singular: "Minute per mile",
      plural: "Minutes per mile"
    },
    to_anchor: 0.0113636
  },
  "s/ft": {
    name: {
      singular: "Second per foot",
      plural: "Seconds per foot"
    },
    to_anchor: 1
  }
};
var measure16 = {
  systems: {
    metric: metric8,
    imperial: imperial6
  },
  anchors: {
    metric: {
      imperial: {
        ratio: 0.3048
      }
    },
    imperial: {
      metric: {
        ratio: {
          numerator: 1,
          denominator: 0.3048
        }
      }
    }
  }
};
var pace_default = measure16;

// node_modules/convert-units/lib/esm/definitions/partsPer.js
var SI8 = {
  ppm: {
    name: {
      singular: "Part-per Million",
      plural: "Parts-per Million"
    },
    to_anchor: 1
  },
  ppb: {
    name: {
      singular: "Part-per Billion",
      plural: "Parts-per Billion"
    },
    to_anchor: 1e-3
  },
  ppt: {
    name: {
      singular: "Part-per Trillion",
      plural: "Parts-per Trillion"
    },
    to_anchor: 1e-6
  },
  ppq: {
    name: {
      singular: "Part-per Quadrillion",
      plural: "Parts-per Quadrillion"
    },
    to_anchor: 1e-9
  }
};
var measure17 = {
  systems: {
    SI: SI8
  }
};
var partsPer_default = measure17;

// node_modules/convert-units/lib/esm/definitions/pieces.js
var unit2 = {
  pcs: {
    name: {
      singular: "Piece",
      plural: "Pieces"
    },
    to_anchor: 1
  },
  "bk-doz": {
    name: {
      singular: "Bakers Dozen",
      plural: "Bakers Dozen"
    },
    to_anchor: 13
  },
  cp: {
    name: {
      singular: "Couple",
      plural: "Couples"
    },
    to_anchor: 2
  },
  "doz-doz": {
    name: {
      singular: "Dozen Dozen",
      plural: "Dozen Dozen"
    },
    to_anchor: 144
  },
  doz: {
    name: {
      singular: "Dozen",
      plural: "Dozens"
    },
    to_anchor: 12
  },
  "gr-gr": {
    name: {
      singular: "Great Gross",
      plural: "Great Gross"
    },
    to_anchor: 1728
  },
  gros: {
    name: {
      singular: "Gross",
      plural: "Gross"
    },
    to_anchor: 144
  },
  "half-dozen": {
    name: {
      singular: "Half Dozen",
      plural: "Half Dozen"
    },
    to_anchor: 6
  },
  "long-hundred": {
    name: {
      singular: "Long Hundred",
      plural: "Long Hundred"
    },
    to_anchor: 120
  },
  ream: {
    name: {
      singular: "Reams",
      plural: "Reams"
    },
    to_anchor: 500
  },
  scores: {
    name: {
      singular: "Scores",
      plural: "Scores"
    },
    to_anchor: 20
  },
  "sm-gr": {
    name: {
      singular: "Small Gross",
      plural: "Small Gross"
    },
    to_anchor: 120
  },
  trio: {
    name: {
      singular: "Trio",
      plural: "Trio"
    },
    to_anchor: 3
  }
};
var measure18 = {
  systems: {
    unit: unit2
  }
};
var pieces_default = measure18;

// node_modules/convert-units/lib/esm/definitions/power.js
var metric9 = {
  W: {
    name: {
      singular: "Watt",
      plural: "Watts"
    },
    to_anchor: 1
  },
  mW: {
    name: {
      singular: "Milliwatt",
      plural: "Milliwatts"
    },
    to_anchor: 1e-3
  },
  kW: {
    name: {
      singular: "Kilowatt",
      plural: "Kilowatts"
    },
    to_anchor: 1e3
  },
  MW: {
    name: {
      singular: "Megawatt",
      plural: "Megawatts"
    },
    to_anchor: 1e6
  },
  GW: {
    name: {
      singular: "Gigawatt",
      plural: "Gigawatts"
    },
    to_anchor: 1e9
  },
  PS: {
    name: {
      singular: "Horsepower (metric)",
      plural: "Horsepower (metric)"
    },
    to_anchor: 735.49875
  }
};
var imperial7 = {
  "Btu/s": {
    name: {
      singular: "British thermal unit per second",
      plural: "British thermal units per second"
    },
    to_anchor: 778.16937
  },
  "ft-lb/s": {
    name: {
      singular: "Foot-pound per second",
      plural: "Foot-pounds per second"
    },
    to_anchor: 1
  },
  hp: {
    name: {
      singular: "Horsepower (British)",
      plural: "Horsepower (British)"
    },
    to_anchor: 550
  }
};
var measure19 = {
  systems: {
    metric: metric9,
    imperial: imperial7
  },
  anchors: {
    metric: {
      imperial: {
        ratio: 0.737562149
      }
    },
    imperial: {
      metric: {
        ratio: {
          numerator: 1,
          denominator: 0.737562149
        }
      }
    }
  }
};
var power_default = measure19;

// node_modules/convert-units/lib/esm/definitions/pressure.js
var metric10 = {
  Pa: {
    name: {
      singular: "pascal",
      plural: "pascals"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e3
    }
  },
  kPa: {
    name: {
      singular: "kilopascal",
      plural: "kilopascals"
    },
    to_anchor: 1
  },
  MPa: {
    name: {
      singular: "megapascal",
      plural: "megapascals"
    },
    to_anchor: 1e3
  },
  hPa: {
    name: {
      singular: "hectopascal",
      plural: "hectopascals"
    },
    to_anchor: {
      numerator: 1,
      denominator: 10
    }
  },
  mbar: {
    name: {
      singular: "millibar",
      plural: "millibar"
    },
    to_anchor: 0.1
  },
  bar: {
    name: {
      singular: "bar",
      plural: "bar"
    },
    to_anchor: 100
  },
  torr: {
    name: {
      singular: "torr",
      plural: "torr"
    },
    to_anchor: {
      numerator: 101325,
      denominator: 76e4
    }
  },
  mH2O: {
    name: {
      singular: "meter of water @ 4\xB0C",
      plural: "meters of water @ 4\xB0C"
    },
    to_anchor: 9.80665
  },
  mmHg: {
    name: {
      singular: "millimeter of mercury",
      plural: "millimeters of mercury"
    },
    to_anchor: 0.133322
  }
};
var imperial8 = {
  psi: {
    name: {
      singular: "pound per square inch",
      plural: "pounds per square inch"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e3
    }
  },
  ksi: {
    name: {
      singular: "kilopound per square inch",
      plural: "kilopound per square inch"
    },
    to_anchor: 1
  },
  inHg: {
    name: {
      singular: "Inch of mercury",
      plural: "Inches of mercury"
    },
    to_anchor: 491154e-9
  }
};
var measure20 = {
  systems: {
    metric: metric10,
    imperial: imperial8
  },
  anchors: {
    metric: {
      imperial: {
        ratio: 14503768078e-14
      }
    },
    imperial: {
      metric: {
        ratio: {
          numerator: 1,
          denominator: 14503768078e-14
        }
      }
    }
  }
};
var pressure_default = measure20;

// node_modules/convert-units/lib/esm/definitions/reactiveEnergy.js
var SI9 = {
  VARh: {
    name: {
      singular: "Volt-Ampere Reactive Hour",
      plural: "Volt-Amperes Reactive Hour"
    },
    to_anchor: 1
  },
  mVARh: {
    name: {
      singular: "Millivolt-Ampere Reactive Hour",
      plural: "Millivolt-Amperes Reactive Hour"
    },
    to_anchor: 1e-3
  },
  kVARh: {
    name: {
      singular: "Kilovolt-Ampere Reactive Hour",
      plural: "Kilovolt-Amperes Reactive Hour"
    },
    to_anchor: 1e3
  },
  MVARh: {
    name: {
      singular: "Megavolt-Ampere Reactive Hour",
      plural: "Megavolt-Amperes Reactive Hour"
    },
    to_anchor: 1e6
  },
  GVARh: {
    name: {
      singular: "Gigavolt-Ampere Reactive Hour",
      plural: "Gigavolt-Amperes Reactive Hour"
    },
    to_anchor: 1e9
  }
};
var measure21 = {
  systems: {
    SI: SI9
  }
};
var reactiveEnergy_default = measure21;

// node_modules/convert-units/lib/esm/definitions/reactivePower.js
var SI10 = {
  VAR: {
    name: {
      singular: "Volt-Ampere Reactive",
      plural: "Volt-Amperes Reactive"
    },
    to_anchor: 1
  },
  mVAR: {
    name: {
      singular: "Millivolt-Ampere Reactive",
      plural: "Millivolt-Amperes Reactive"
    },
    to_anchor: 1e-3
  },
  kVAR: {
    name: {
      singular: "Kilovolt-Ampere Reactive",
      plural: "Kilovolt-Amperes Reactive"
    },
    to_anchor: 1e3
  },
  MVAR: {
    name: {
      singular: "Megavolt-Ampere Reactive",
      plural: "Megavolt-Amperes Reactive"
    },
    to_anchor: 1e6
  },
  GVAR: {
    name: {
      singular: "Gigavolt-Ampere Reactive",
      plural: "Gigavolt-Amperes Reactive"
    },
    to_anchor: 1e9
  }
};
var measure22 = {
  systems: {
    SI: SI10
  }
};
var reactivePower_default = measure22;

// node_modules/convert-units/lib/esm/definitions/speed.js
var metric11 = {
  "m/s": {
    name: {
      singular: "Metre per second",
      plural: "Metres per second"
    },
    to_anchor: 3.6
  },
  "km/h": {
    name: {
      singular: "Kilometre per hour",
      plural: "Kilometres per hour"
    },
    to_anchor: 1
  },
  "mm/h": {
    name: {
      singular: "Millimeter per hour",
      plural: "Millimeters per hour"
    },
    to_anchor: 1e-6
  }
};
var imperial9 = {
  mph: {
    name: {
      singular: "Mile per hour",
      plural: "Miles per hour"
    },
    to_anchor: 1
  },
  knot: {
    name: {
      singular: "Knot",
      plural: "Knots"
    },
    to_anchor: 1.150779
  },
  "ft/s": {
    name: {
      singular: "Foot per second",
      plural: "Feet per second"
    },
    to_anchor: 0.681818
  },
  "ft/min": {
    name: {
      singular: "Foot per minute",
      plural: "Feet per minute"
    },
    to_anchor: 0.0113636
  },
  "in/h": {
    name: {
      singular: "Inch per hour",
      plural: "Inches per hour"
    },
    to_anchor: 1578e-8
  }
};
var measure23 = {
  systems: {
    metric: metric11,
    imperial: imperial9
  },
  anchors: {
    metric: {
      imperial: {
        ratio: {
          numerator: 1,
          denominator: 1.609344
        }
      }
    },
    imperial: {
      metric: {
        ratio: 1.609344
      }
    }
  }
};
var speed_default = measure23;

// node_modules/convert-units/lib/esm/definitions/temperature.js
var metric12 = {
  C: {
    name: {
      singular: "degree Celsius",
      plural: "degrees Celsius"
    },
    to_anchor: 1,
    anchor_shift: 0
  },
  K: {
    name: {
      singular: "Kelvin",
      plural: "Kelvins"
    },
    to_anchor: 1,
    anchor_shift: 273.15
  }
};
var imperial10 = {
  F: {
    name: {
      singular: "degree Fahrenheit",
      plural: "degrees Fahrenheit"
    },
    to_anchor: 1
  },
  R: {
    name: {
      singular: "degree Rankine",
      plural: "degrees Rankine"
    },
    to_anchor: 1,
    anchor_shift: 459.67
  }
};
var measure24 = {
  systems: {
    metric: metric12,
    imperial: imperial10
  },
  anchors: {
    metric: {
      imperial: {
        transform: function(C, cls) {
          return cls.add(cls.div(C, cls.div(5, 9)), 32);
        }
      }
    },
    imperial: {
      metric: {
        transform: function(F, cls) {
          return cls.mul(cls.sub(F, 32), cls.div(5, 9));
        }
      }
    }
  }
};
var temperature_default = measure24;

// node_modules/convert-units/lib/esm/definitions/time.js
var SI11 = {
  ns: {
    name: {
      singular: "Nanosecond",
      plural: "Nanoseconds"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e9
    }
  },
  mu: {
    name: {
      singular: "Microsecond",
      plural: "Microseconds"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e6
    }
  },
  ms: {
    name: {
      singular: "Millisecond",
      plural: "Milliseconds"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e3
    }
  },
  s: {
    name: {
      singular: "Second",
      plural: "Seconds"
    },
    to_anchor: 1
  },
  min: {
    name: {
      singular: "Minute",
      plural: "Minutes"
    },
    to_anchor: 60
  },
  h: {
    name: {
      singular: "Hour",
      plural: "Hours"
    },
    to_anchor: 3600
    // 60 * 60
  },
  d: {
    name: {
      singular: "Day",
      plural: "Days"
    },
    to_anchor: 86400
    // 60 * 60 * 24
  },
  week: {
    name: {
      singular: "Week",
      plural: "Weeks"
    },
    to_anchor: 604800
    // 60 * 60 * 24 * 7
  },
  month: {
    name: {
      singular: "Month",
      plural: "Months"
    },
    to_anchor: {
      numerator: 31557600,
      // 60 * 60 * 24 * 365.25
      denominator: 12
    }
  },
  year: {
    name: {
      singular: "Year",
      plural: "Years"
    },
    to_anchor: 31557600
    // 60 * 60 * 24 * 365.25,
  }
};
var measure25 = {
  systems: {
    SI: SI11
  }
};
var time_default = measure25;

// node_modules/convert-units/lib/esm/definitions/torque.js
var metric13 = {
  Nm: {
    name: {
      singular: "Newton-meter",
      plural: "Newton-meters"
    },
    to_anchor: 1
  },
  cNm: {
    name: {
      singular: "Centinewton-meter",
      plural: "Centinewton-meters"
    },
    to_anchor: 0.01
  },
  dNm: {
    name: {
      singular: "Decinewton-meter",
      plural: "Decinewton-meters"
    },
    to_anchor: 0.1
  },
  kgm: {
    name: {
      singular: "Kilogram-meter",
      plural: "Kilogram-meters"
    },
    to_anchor: 9.806649999787735
    // 1 / 0.1019716213,
  },
  "kg-cm": {
    name: {
      singular: "Kilogram-centimeter",
      plural: "Kilogram-centimeters"
    },
    to_anchor: 0.09806649999787735
    // 1 / 10.19716213,
  }
};
var imperial11 = {
  "lbf-ft": {
    name: {
      singular: "Pound-foot",
      plural: "Pound-feet"
    },
    to_anchor: 1
  },
  "lbf-in": {
    name: {
      singular: "Pound-inch",
      plural: "Pound-inches"
    },
    to_anchor: 0.08333333333333333
    // 1 / 12,
  },
  "ozf-in": {
    name: {
      singular: "Ounce-inch",
      plural: "Ounce-inches"
    },
    to_anchor: 0.005208333271755643
    // 1 / 192.00000227,
  }
};
var measure26 = {
  systems: {
    metric: metric13,
    imperial: imperial11
  },
  anchors: {
    metric: {
      imperial: {
        ratio: {
          numerator: 1,
          denominator: 1.355818
        }
      }
    },
    imperial: {
      metric: {
        ratio: 1.355818
      }
    }
  }
};
var torque_default = measure26;

// node_modules/convert-units/lib/esm/definitions/voltage.js
var SI12 = {
  V: {
    name: {
      singular: "Volt",
      plural: "Volts"
    },
    to_anchor: 1
  },
  \u03BCV: {
    name: {
      singular: "Microvolt",
      plural: "Microvolts"
    },
    to_anchor: 1e-6
  },
  mV: {
    name: {
      singular: "Millivolt",
      plural: "Millivolts"
    },
    to_anchor: 1e-3
  },
  kV: {
    name: {
      singular: "Kilovolt",
      plural: "Kilovolts"
    },
    to_anchor: 1e3
  },
  MV: {
    name: {
      singular: "Megavolt",
      plural: "Megavolts"
    },
    to_anchor: 1e6
  }
};
var measure27 = {
  systems: {
    SI: SI12
  }
};
var voltage_default = measure27;

// node_modules/convert-units/lib/esm/definitions/volume.js
var metric14 = {
  mm3: {
    name: {
      singular: "Cubic Millimeter",
      plural: "Cubic Millimeters"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e6
    }
  },
  cm3: {
    name: {
      singular: "Cubic Centimeter",
      plural: "Cubic Centimeters"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e3
    }
  },
  dm3: {
    name: {
      singular: "Cubic Decimeter",
      plural: "Cubic Decimeters"
    },
    to_anchor: 1
  },
  ml: {
    name: {
      singular: "Millilitre",
      plural: "Millilitres"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e3
    }
  },
  cl: {
    name: {
      singular: "Centilitre",
      plural: "Centilitres"
    },
    to_anchor: {
      numerator: 1,
      denominator: 100
    }
  },
  dl: {
    name: {
      singular: "Decilitre",
      plural: "Decilitres"
    },
    to_anchor: {
      numerator: 1,
      denominator: 10
    }
  },
  l: {
    name: {
      singular: "Litre",
      plural: "Litres"
    },
    to_anchor: 1
  },
  kl: {
    name: {
      singular: "Kilolitre",
      plural: "Kilolitres"
    },
    to_anchor: 1e3
  },
  Ml: {
    name: {
      singular: "Megalitre",
      plural: "Megalitres"
    },
    to_anchor: 1e6
  },
  Gl: {
    name: {
      singular: "Gigalitre",
      plural: "Gigalitres"
    },
    to_anchor: 1e9
  },
  m3: {
    name: {
      singular: "Cubic meter",
      plural: "Cubic meters"
    },
    to_anchor: 1e3
  },
  km3: {
    name: {
      singular: "Cubic kilometer",
      plural: "Cubic kilometers"
    },
    to_anchor: 1e12
  },
  // Swedish units
  krm: {
    name: {
      singular: "Kryddm\xE5tt",
      plural: "Kryddm\xE5tt"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e3
    }
  },
  tsk: {
    name: {
      singular: "Tesked",
      plural: "Teskedar"
    },
    to_anchor: {
      numerator: 5,
      denominator: 1e3
    }
  },
  msk: {
    name: {
      singular: "Matsked",
      plural: "Matskedar"
    },
    to_anchor: {
      numerator: 15,
      denominator: 1e3
    }
  },
  kkp: {
    name: {
      singular: "Kaffekopp",
      plural: "Kaffekoppar"
    },
    to_anchor: {
      numerator: 150,
      denominator: 1e3
    }
  },
  glas: {
    name: {
      singular: "Glas",
      plural: "Glas"
    },
    to_anchor: {
      numerator: 200,
      denominator: 1e3
    }
  },
  kanna: {
    name: {
      singular: "Kanna",
      plural: "Kannor"
    },
    to_anchor: 2.617
  }
};
var imperial12 = {
  tsp: {
    name: {
      singular: "Teaspoon",
      plural: "Teaspoons"
    },
    to_anchor: {
      numerator: 1,
      denominator: 6
    }
  },
  Tbs: {
    name: {
      singular: "Tablespoon",
      plural: "Tablespoons"
    },
    to_anchor: {
      numerator: 1,
      denominator: 2
    }
  },
  in3: {
    name: {
      singular: "Cubic inch",
      plural: "Cubic inches"
    },
    to_anchor: 0.55411
  },
  "fl-oz": {
    name: {
      singular: "Fluid Ounce",
      plural: "Fluid Ounces"
    },
    to_anchor: 1
  },
  cup: {
    name: {
      singular: "Cup",
      plural: "Cups"
    },
    to_anchor: 8
  },
  pnt: {
    name: {
      singular: "Pint",
      plural: "Pints"
    },
    to_anchor: 16
  },
  qt: {
    name: {
      singular: "Quart",
      plural: "Quarts"
    },
    to_anchor: 32
  },
  gal: {
    name: {
      singular: "Gallon",
      plural: "Gallons"
    },
    to_anchor: 128
  },
  ft3: {
    name: {
      singular: "Cubic foot",
      plural: "Cubic feet"
    },
    to_anchor: 957.506
  },
  yd3: {
    name: {
      singular: "Cubic yard",
      plural: "Cubic yards"
    },
    to_anchor: 25852.7
  }
};
var measure28 = {
  systems: {
    metric: metric14,
    imperial: imperial12
  },
  anchors: {
    metric: {
      imperial: {
        ratio: 33.8140226
      }
    },
    imperial: {
      metric: {
        ratio: {
          numerator: 1,
          denominator: 33.8140226
        }
      }
    }
  }
};
var volume_default = measure28;

// node_modules/convert-units/lib/esm/definitions/volumeFlowRate.js
var metric15 = {
  "mm3/s": {
    name: {
      singular: "Cubic Millimeter per second",
      plural: "Cubic Millimeters per second"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e6
    }
  },
  "cm3/s": {
    name: {
      singular: "Cubic Centimeter per second",
      plural: "Cubic Centimeters per second"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e3
    }
  },
  "dm3/s": {
    name: {
      singular: "Cubic Decimeter per second",
      plural: "Cubic Decimeters per second"
    },
    to_anchor: 1
  },
  "dm3/min": {
    name: {
      singular: "Cubic Decimeter per minute",
      plural: "Cubic Decimeters per minute"
    },
    to_anchor: 1 / 60
  },
  "dm3/h": {
    name: {
      singular: "Cubic Decimeter per hour",
      plural: "Cubic Decimeters per hour"
    },
    to_anchor: 1 / 3600
  },
  "dm3/d": {
    name: {
      singular: "Cubic Decimeter per day",
      plural: "Cubic Decimeters per day"
    },
    to_anchor: 1 / 86400
  },
  "dm3/a": {
    name: {
      singular: "Cubic Decimeter per year",
      plural: "Cubic Decimeters per year"
    },
    to_anchor: 1 / 31557600
  },
  "ml/s": {
    name: {
      singular: "Millilitre per second",
      plural: "Millilitres per second"
    },
    to_anchor: {
      numerator: 1,
      denominator: 1e3
    }
  },
  "cl/s": {
    name: {
      singular: "Centilitre per second",
      plural: "Centilitres per second"
    },
    to_anchor: {
      numerator: 1,
      denominator: 100
    }
  },
  "dl/s": {
    name: {
      singular: "Decilitre per second",
      plural: "Decilitres per second"
    },
    to_anchor: {
      numerator: 1,
      denominator: 10
    }
  },
  "l/s": {
    name: {
      singular: "Litre per second",
      plural: "Litres per second"
    },
    to_anchor: 1
  },
  "l/min": {
    name: {
      singular: "Litre per minute",
      plural: "Litres per minute"
    },
    to_anchor: {
      numerator: 1,
      denominator: 60
    }
  },
  "l/h": {
    name: {
      singular: "Litre per hour",
      plural: "Litres per hour"
    },
    to_anchor: {
      numerator: 1,
      denominator: 3600
    }
  },
  "l/d": {
    name: {
      singular: "Litre per day",
      plural: "Litres per day"
    },
    to_anchor: 1 / 86400
  },
  "l/a": {
    name: {
      singular: "Litre per year",
      plural: "Litres per year"
    },
    to_anchor: 1 / 31557600
  },
  "kl/s": {
    name: {
      singular: "Kilolitre per second",
      plural: "Kilolitres per second"
    },
    to_anchor: 1e3
  },
  "kl/min": {
    name: {
      singular: "Kilolitre per minute",
      plural: "Kilolitres per minute"
    },
    to_anchor: {
      numerator: 50,
      denominator: 3
    }
  },
  "kl/h": {
    name: {
      singular: "Kilolitre per hour",
      plural: "Kilolitres per hour"
    },
    to_anchor: {
      numerator: 5,
      denominator: 18
    }
  },
  "m3/s": {
    name: {
      singular: "Cubic meter per second",
      plural: "Cubic meters per second"
    },
    to_anchor: 1e3
  },
  "m3/min": {
    name: {
      singular: "Cubic meter per minute",
      plural: "Cubic meters per minute"
    },
    to_anchor: {
      numerator: 50,
      denominator: 3
    }
  },
  "m3/h": {
    name: {
      singular: "Cubic meter per hour",
      plural: "Cubic meters per hour"
    },
    to_anchor: {
      numerator: 5,
      denominator: 18
    }
  },
  "m3/d": {
    name: {
      singular: "Cubic meter per day",
      plural: "Cubic meters per day"
    },
    to_anchor: 5 / 432
  },
  "m3/a": {
    name: {
      singular: "Cubic meter per year",
      plural: "Cubic meters per year"
    },
    to_anchor: 5 / 157788
  },
  "km3/s": {
    name: {
      singular: "Cubic kilometer per second",
      plural: "Cubic kilometers per second"
    },
    to_anchor: 1e12
  }
};
var imperial13 = {
  "tsp/s": {
    name: {
      singular: "Teaspoon per second",
      plural: "Teaspoons per second"
    },
    to_anchor: {
      numerator: 1,
      denominator: 6
    }
  },
  "Tbs/s": {
    name: {
      singular: "Tablespoon per second",
      plural: "Tablespoons per second"
    },
    to_anchor: {
      numerator: 1,
      denominator: 2
    }
  },
  "in3/s": {
    name: {
      singular: "Cubic inch per second",
      plural: "Cubic inches per second"
    },
    to_anchor: 0.55411
  },
  "in3/min": {
    name: {
      singular: "Cubic inch per minute",
      plural: "Cubic inches per minute"
    },
    to_anchor: {
      numerator: 0.55411,
      denominator: 60
    }
  },
  "in3/h": {
    name: {
      singular: "Cubic inch per hour",
      plural: "Cubic inches per hour"
    },
    to_anchor: {
      numerator: 0.55411,
      denominator: 3600
    }
  },
  "fl-oz/s": {
    name: {
      singular: "Fluid Ounce per second",
      plural: "Fluid Ounces per second"
    },
    to_anchor: 1
  },
  "fl-oz/min": {
    name: {
      singular: "Fluid Ounce per minute",
      plural: "Fluid Ounces per minute"
    },
    to_anchor: {
      numerator: 1,
      denominator: 60
    }
  },
  "fl-oz/h": {
    name: {
      singular: "Fluid Ounce per hour",
      plural: "Fluid Ounces per hour"
    },
    to_anchor: {
      numerator: 1,
      denominator: 3600
    }
  },
  "cup/s": {
    name: {
      singular: "Cup per second",
      plural: "Cups per second"
    },
    to_anchor: 8
  },
  "pnt/s": {
    name: {
      singular: "Pint per second",
      plural: "Pints per second"
    },
    to_anchor: 16
  },
  "pnt/min": {
    name: {
      singular: "Pint per minute",
      plural: "Pints per minute"
    },
    to_anchor: {
      numerator: 4,
      denominator: 15
    }
  },
  "pnt/h": {
    name: {
      singular: "Pint per hour",
      plural: "Pints per hour"
    },
    to_anchor: {
      numerator: 1,
      denominator: 225
    }
  },
  "qt/s": {
    name: {
      singular: "Quart per second",
      plural: "Quarts per second"
    },
    to_anchor: 32
  },
  "gal/s": {
    name: {
      singular: "Gallon per second",
      plural: "Gallons per second"
    },
    to_anchor: 128
  },
  "gal/min": {
    name: {
      singular: "Gallon per minute",
      plural: "Gallons per minute"
    },
    to_anchor: {
      numerator: 32,
      denominator: 15
    }
  },
  "gal/h": {
    name: {
      singular: "Gallon per hour",
      plural: "Gallons per hour"
    },
    to_anchor: {
      numerator: 8,
      denominator: 225
    }
  },
  "ft3/s": {
    name: {
      singular: "Cubic foot per second",
      plural: "Cubic feet per second"
    },
    to_anchor: 957.506
  },
  "ft3/min": {
    name: {
      singular: "Cubic foot per minute",
      plural: "Cubic feet per minute"
    },
    to_anchor: {
      numerator: 957.506,
      denominator: 60
    }
  },
  "ft3/h": {
    name: {
      singular: "Cubic foot per hour",
      plural: "Cubic feet per hour"
    },
    to_anchor: {
      numerator: 957.506,
      denominator: 3600
    }
  },
  "yd3/s": {
    name: {
      singular: "Cubic yard per second",
      plural: "Cubic yards per second"
    },
    to_anchor: 25852.7
  },
  "yd3/min": {
    name: {
      singular: "Cubic yard per minute",
      plural: "Cubic yards per minute"
    },
    to_anchor: {
      numerator: 25852.7,
      denominator: 60
    }
  },
  "yd3/h": {
    name: {
      singular: "Cubic yard per hour",
      plural: "Cubic yards per hour"
    },
    to_anchor: {
      numerator: 25852.7,
      denominator: 3600
    }
  }
};
var measure29 = {
  systems: {
    metric: metric15,
    imperial: imperial13
  },
  anchors: {
    metric: {
      imperial: {
        ratio: 33.8140227
      }
    },
    imperial: {
      metric: {
        ratio: {
          numerator: 1,
          denominator: 33.8140227
        }
      }
    }
  }
};
var volumeFlowRate_default = measure29;

// node_modules/convert-units/lib/esm/definitions/all.js
var allMeasures = {
  acceleration: acceleration_default,
  angle: angle_default,
  apparentPower: apparentPower_default,
  area: area_default,
  charge: charge_default,
  current: current_default,
  digital: digital_default,
  each: each_default2,
  energy: energy_default,
  force: force_default,
  frequency: frequency_default,
  illuminance: illuminance_default,
  length: length_default,
  mass: mass_default,
  massFlowRate: massFlowRate_default,
  pace: pace_default,
  partsPer: partsPer_default,
  pieces: pieces_default,
  power: power_default,
  pressure: pressure_default,
  reactiveEnergy: reactiveEnergy_default,
  reactivePower: reactivePower_default,
  speed: speed_default,
  torque: torque_default,
  temperature: temperature_default,
  time: time_default,
  voltage: voltage_default,
  volume: volume_default,
  volumeFlowRate: volumeFlowRate_default
};
var all_default = allMeasures;

// src/transfer.mts
var convert = configureMeasurements(all_default);
function transfer(seis, response, lowCut, lowPass, highPass, highCut) {
  if (!response) {
    throw new Error("Response not exist???");
  }
  const sacPoleZero = convertToSacPoleZero(response);
  return transferSacPZ(seis, sacPoleZero, lowCut, lowPass, highPass, highCut);
}
function transferSacPZ(seis, sacPoleZero, lowCut, lowPass, highPass, highCut) {
  const outSeis = [];
  for (let i = 0; i < seis.segments.length; i++) {
    const result = transferSacPZSegment(
      seis.segments[i],
      sacPoleZero,
      lowCut,
      lowPass,
      highPass,
      highCut
    );
    outSeis.push(result);
  }
  return new Seismogram(outSeis);
}
function transferSacPZSegment(seis, sacPoleZero, lowCut, lowPass, highPass, highCut) {
  const sampFreq = seis.sampleRate;
  const values = seis.y;
  let outData = Float32Array.from(values);
  outData.forEach((d, i) => outData[i] = d / sampFreq);
  let freqValues = calcDFT(outData);
  freqValues = combine(
    freqValues,
    sampFreq,
    sacPoleZero,
    lowCut,
    lowPass,
    highPass,
    highCut
  );
  outData = inverseDFT(freqValues, values.length);
  outData.forEach((d, i) => outData[i] = d * freqValues.length);
  const out = seis.cloneWithNewData(outData);
  out.yUnit = "m";
  return out;
}
function calcResponse(response, numPoints, sampleRate, unit3) {
  const sacPoleZero = convertToSacPoleZero(response);
  const siUnit = unit3.replaceAll("**", "");
  const unitQty = convert(1).getUnit(siUnit);
  let gamma2;
  if (unitQty === null) {
    throw new Error("unknown response unit: " + unit3);
  } else if (unitQty.measure === "length") {
    gamma2 = 0;
  } else if (unitQty.measure === "speed") {
    gamma2 = 1;
  } else if (unitQty.measure === "acceleration") {
    gamma2 = 2;
  } else {
    throw new Error(
      "response unit is not displacement (m), velocity (m/s) or acceleration (m/s^2): " + unit3
    );
  }
  sacPoleZero.trimZeros(gamma2);
  const out = calcResponseFromSacPoleZero(sacPoleZero, numPoints, sampleRate);
  return out;
}
function calcResponseFromSacPoleZero(sacPoleZero, numPoints, sampleRate) {
  const deltaF = sampleRate / numPoints;
  const freqValues = new Float32Array(numPoints);
  let respAtS;
  respAtS = evalPoleZeroInverse(sacPoleZero, 0);
  respAtS = new Complex(1, 0).overComplex(respAtS);
  freqValues[0] = respAtS.real();
  let freq = sampleRate / 2;
  respAtS = evalPoleZeroInverse(sacPoleZero, freq);
  respAtS = new Complex(1, 0).overComplex(respAtS);
  freqValues[freqValues.length / 2] = respAtS.real();
  for (let i = 1; i < freqValues.length / 2; i++) {
    freq = i * deltaF;
    respAtS = evalPoleZeroInverse(sacPoleZero, freq);
    respAtS = new Complex(1, 0).overComplex(respAtS);
    if (respAtS.real() !== 0 || respAtS.imag() !== 0) {
      freqValues[i] = respAtS.real();
      freqValues[freqValues.length - i] = respAtS.imag();
    } else {
      freqValues[i] = 1e-10;
      freqValues[freqValues.length - i] = 0;
    }
  }
  const out = FFTResult.createFromPackedFreq(freqValues, numPoints, sampleRate);
  return out;
}
function combine(freqValues, sampFreq, sacPoleZero, lowCut, lowPass, highPass, highCut) {
  const deltaF = sampFreq / freqValues.length;
  freqValues[0] = 0;
  let freq = sampFreq / 2;
  let respAtS = evalPoleZeroInverse(sacPoleZero, freq);
  respAtS = respAtS.timesReal(
    deltaF * calcFreqTaper(freq, lowCut, lowPass, highPass, highCut)
  );
  freqValues[freqValues.length / 2] = respAtS.timesReal(freqValues[freqValues.length / 2]).real();
  for (let i = 1; i < freqValues.length / 2; i++) {
    freq = i * deltaF;
    respAtS = evalPoleZeroInverse(sacPoleZero, freq);
    respAtS = respAtS.timesReal(
      deltaF * calcFreqTaper(freq, lowCut, lowPass, highPass, highCut)
    );
    const freqComplex = new Complex(
      freqValues[i],
      freqValues[freqValues.length - i]
    ).timesComplex(respAtS);
    freqValues[i] = freqComplex.real();
    freqValues[freqValues.length - i] = freqComplex.imag();
  }
  return freqValues;
}
function evalPoleZeroInverse(sacPoleZero, freq) {
  return sacPoleZero.evalPoleZeroInverse(freq);
}
function calcFreqTaper(freq, lowCut, lowPass, highPass, highCut) {
  if (lowCut > lowPass || lowPass > highPass || highPass > highCut) {
    throw new Error(
      "must be lowCut > lowPass > highPass > highCut: " + lowCut + " " + lowPass + " " + highPass + " " + highCut
    );
  }
  if (freq <= lowCut || freq >= highCut) {
    return 0;
  }
  if (freq >= lowPass && freq <= highPass) {
    return 1;
  }
  if (freq > lowCut && freq < lowPass) {
    return 0.5 * (1 + Math.cos(Math.PI * (freq - lowPass) / (lowCut - lowPass)));
  }
  return 0.5 * (1 - Math.cos(Math.PI * (freq - highCut) / (highPass - highCut)));
}
function applyFreqTaper(fftResult, sampleRate, lowCut, lowPass, highPass, highCut) {
  const deltaF = fftResult.fundamentalFrequency;
  return FFTResult.createFromAmpPhase(
    fftResult.amplitudes().map(
      (v, i) => i === 0 ? 0 : v * calcFreqTaper(i * deltaF, lowCut, lowPass, highPass, highCut)
    ),
    fftResult.phases(),
    fftResult.origLength,
    fftResult.sampleRate
  );
}
var METER = convert().getUnit("m");
var METER_PER_SECOND = convert().getUnit("m/s");
var METER_PER_SECOND_PER_SECOND = convert().getUnit("m/s2");
function calcGamma(unit3) {
  let gamma2;
  const unitQty = convert(1).getUnit(unit3);
  if (unitQty === null) {
    throw new Error("unknown response unit: " + unit3);
  } else if (unitQty.measure === "length") {
    gamma2 = 0;
  } else if (unitQty.measure === "speed") {
    gamma2 = 1;
  } else if (unitQty.measure === "acceleration") {
    gamma2 = 2;
  } else {
    throw new Error(
      "response unit is not displacement (m), velocity (m/s) or acceleration (m/s^2): " + unit3
    );
  }
  return gamma2;
}
function calcScaleUnit(unit3) {
  let scale;
  const unitQty = convert(1).getUnit(unit3);
  if (unitQty === null) {
    throw new Error("unknown response unit: " + unit3);
  } else if (unitQty.measure === "length") {
    scale = convert(1).from(unit3).to("m");
  } else if (unitQty.measure === "speed") {
    scale = convert(1).from(unit3).to("m/s");
  } else if (unitQty.measure === "acceleration") {
    scale = convert(1).from(unit3).to("m/s2");
  } else {
    throw new Error(
      "response unit is not displacement (m), velocity (m/s) or acceleration (m/s^2): " + unit3
    );
  }
  return scale;
}
function convertToSacPoleZero(response) {
  let polesZeros;
  if (response.stages[0].filter instanceof PolesZeros) {
    polesZeros = response.stages[0].filter;
  } else {
    throw new Error("can't find PolesZeros");
  }
  if (response.instrumentSensitivity === null) {
    throw new Error("response.instrumentSensitivity missing");
  }
  let unit3 = response.instrumentSensitivity.inputUnits;
  unit3 = unit3.replaceAll("**", "");
  if (unit3 === "M") {
    unit3 = "m";
  }
  if (unit3 === "M/S" || unit3 === "M/SEC") {
    unit3 = "m/s";
  }
  if (unit3 === "M/S2" || unit3 === "M/SEC2") {
    unit3 = "m/s2";
  }
  const gamma2 = calcGamma(unit3);
  const scaleUnit = calcScaleUnit(unit3);
  const scale_sensitivity = scaleUnit * response.instrumentSensitivity.sensitivity;
  return convertPoleZeroToSacStyle(
    polesZeros,
    scale_sensitivity,
    response.instrumentSensitivity.frequency,
    gamma2
  );
}
function convertPoleZeroToSacStyle(polesZeros, sensitivity, sensitivity_freq, gamma2) {
  let mulFactor = 1;
  if (polesZeros.pzTransferFunctionType === "LAPLACE (HERTZ)") {
    mulFactor = 2 * Math.PI;
  }
  const zeros = [];
  for (let i = 0; i < polesZeros.zeros.length; i++) {
    zeros[i] = new Complex(
      polesZeros.zeros[i].real() * mulFactor,
      polesZeros.zeros[i].imag() * mulFactor
    );
  }
  for (let i = 0; i < gamma2; i++) {
    zeros.push(new Complex(0, 0));
  }
  const poles = [];
  for (let i = 0; i < polesZeros.poles.length; i++) {
    poles[i] = new Complex(
      polesZeros.poles[i].real() * mulFactor,
      polesZeros.poles[i].imag() * mulFactor
    );
  }
  let sd = sensitivity;
  const fs = sensitivity_freq;
  sd *= Math.pow(2 * Math.PI * fs, gamma2);
  let A0 = polesZeros.normalizationFactor;
  const fn = polesZeros.normalizationFrequency;
  A0 = A0 / Math.pow(2 * Math.PI * fn, gamma2);
  if (polesZeros.pzTransferFunctionType === "LAPLACE (HERTZ)") {
    A0 *= Math.pow(
      2 * Math.PI,
      polesZeros.poles.length - polesZeros.zeros.length
    );
  }
  let constant;
  if (poles.length === 0 && zeros.length === 0) {
    constant = sd * A0;
  } else {
    constant = sd * calc_A0(poles, zeros, fs);
  }
  const sacPZ = new SacPoleZero(poles, zeros, constant);
  sacPZ.gamma = gamma2;
  sacPZ.mulFactor = mulFactor;
  sacPZ.sd = sd;
  sacPZ.A0 = A0;
  return sacPZ;
}
function calc_A0(poles, zeros, ref_freq) {
  let numer = new Complex(1, 0);
  let denom = new Complex(1, 0);
  const f0 = new Complex(0, 2 * Math.PI * ref_freq);
  for (let i = 0; i < zeros.length; i++) {
    denom = denom.timesComplex(f0.minusComplex(zeros[i]));
  }
  for (let i = 0; i < poles.length; i++) {
    numer = numer.timesComplex(f0.minusComplex(poles[i]));
  }
  const a0 = numer.overComplex(denom).abs();
  return a0;
}

// src/usgsgeojson.mts
var usgsgeojson_exports = {};
__export(usgsgeojson_exports, {
  USGS_TECTONIC_SUMMARY_URL: () => USGS_TECTONIC_SUMMARY_URL,
  daySummaryAllUrl: () => daySummaryAllUrl,
  daySummaryM1_0Url: () => daySummaryM1_0Url,
  daySummaryM2_5Url: () => daySummaryM2_5Url,
  daySummaryM4_5Url: () => daySummaryM4_5Url,
  daySummarySignificantUrl: () => daySummarySignificantUrl,
  hourSummaryAllUrl: () => hourSummaryAllUrl,
  hourSummaryM1_0Url: () => hourSummaryM1_0Url,
  hourSummaryM2_5Url: () => hourSummaryM2_5Url,
  hourSummaryM4_5Url: () => hourSummaryM4_5Url,
  hourSummarySignificantUrl: () => hourSummarySignificantUrl,
  isValidUSGSGeoJsonQuake: () => isValidUSGSGeoJsonQuake,
  isValidUSGSGeoJsonSummary: () => isValidUSGSGeoJsonSummary,
  isValidUSGSTectonic: () => isValidUSGSTectonic,
  isValidUSGSTectonicGeoJsonSummary: () => isValidUSGSTectonicGeoJsonSummary,
  loadDaySummaryAll: () => loadDaySummaryAll,
  loadDaySummaryM1_0: () => loadDaySummaryM1_0,
  loadDaySummaryM2_5: () => loadDaySummaryM2_5,
  loadDaySummaryM4_5: () => loadDaySummaryM4_5,
  loadDaySummarySignificant: () => loadDaySummarySignificant,
  loadHourSummaryAll: () => loadHourSummaryAll,
  loadHourSummaryM1_0: () => loadHourSummaryM1_0,
  loadHourSummaryM2_5: () => loadHourSummaryM2_5,
  loadHourSummaryM4_5: () => loadHourSummaryM4_5,
  loadHourSummarySignificant: () => loadHourSummarySignificant,
  loadMonthSignificant: () => loadMonthSignificant,
  loadMonthSummaryAll: () => loadMonthSummaryAll,
  loadMonthSummaryM1_0: () => loadMonthSummaryM1_0,
  loadMonthSummaryM2_5: () => loadMonthSummaryM2_5,
  loadMonthSummaryM4_5: () => loadMonthSummaryM4_5,
  loadMonthSummarySignificant: () => loadMonthSummarySignificant,
  loadRawUSGSGeoJsonSummary: () => loadRawUSGSGeoJsonSummary,
  loadSignificant: () => loadSignificant,
  loadUSGSGeoJsonSummary: () => loadUSGSGeoJsonSummary,
  loadUSGSSummary: () => loadUSGSSummary,
  loadUSGSTectonicLayer: () => loadUSGSTectonicLayer,
  loadWeekSummaryAll: () => loadWeekSummaryAll,
  loadWeekSummaryM1_0: () => loadWeekSummaryM1_0,
  loadWeekSummaryM2_5: () => loadWeekSummaryM2_5,
  loadWeekSummaryM4_5: () => loadWeekSummaryM4_5,
  loadWeekSummarySignificant: () => loadWeekSummarySignificant,
  loadYearSignificant: () => loadYearSignificant,
  monthSummaryAllUrl: () => monthSummaryAllUrl,
  monthSummaryM1_0Url: () => monthSummaryM1_0Url,
  monthSummaryM2_5Url: () => monthSummaryM2_5Url,
  monthSummaryM4_5Url: () => monthSummaryM4_5Url,
  monthSummarySignificantUrl: () => monthSummarySignificantUrl,
  parseFeatureAsQuake: () => parseFeatureAsQuake,
  parseGeoJSON: () => parseGeoJSON,
  weekSummaryAllUrl: () => weekSummaryAllUrl,
  weekSummaryM1_0Url: () => weekSummaryM1_0Url,
  weekSummaryM2_5Url: () => weekSummaryM2_5Url,
  weekSummaryM4_5Url: () => weekSummaryM4_5Url,
  weekSummarySignificantUrl: () => weekSummarySignificantUrl,
  yearSignificant: () => yearSignificant
});
var timeoutSec = 10;
var hourSummarySignificantUrl = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_hour.geojson";
var hourSummaryM4_5Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_hour.geojson";
var hourSummaryM2_5Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_hour.geojson";
var hourSummaryM1_0Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_hour.geojson";
var hourSummaryAllUrl = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson";
var daySummarySignificantUrl = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_day.geojson";
var daySummaryM4_5Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson";
var daySummaryM2_5Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson";
var daySummaryM1_0Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_day.geojson";
var daySummaryAllUrl = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson";
var weekSummarySignificantUrl = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_week.geojson";
var weekSummaryM4_5Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_week.geojson";
var weekSummaryM2_5Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojson";
var weekSummaryM1_0Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_week.geojson";
var weekSummaryAllUrl = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson";
var monthSummarySignificantUrl = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson";
var monthSummaryM4_5Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.geojson";
var monthSummaryM2_5Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson";
var monthSummaryM1_0Url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_month.geojson";
var monthSummaryAllUrl = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson";
var yearSignificant = "https://earthquake.usgs.gov/fdsnws/event/1/query.geojson?minsig=600";
var USGS_TECTONIC_SUMMARY_URL = "https://earthquake.usgs.gov/ws/geoserve/layers.json?type=tectonic";
function loadHourSummarySignificant() {
  return loadUSGSSummary(hourSummarySignificantUrl);
}
function loadHourSummaryM4_5() {
  return loadUSGSSummary(hourSummaryM4_5Url);
}
function loadHourSummaryM2_5() {
  return loadUSGSSummary(hourSummaryM2_5Url);
}
function loadHourSummaryM1_0() {
  return loadUSGSSummary(hourSummaryM1_0Url);
}
function loadHourSummaryAll() {
  return loadUSGSSummary(hourSummaryAllUrl);
}
function loadDaySummarySignificant() {
  return loadUSGSSummary(daySummarySignificantUrl);
}
function loadDaySummaryM4_5() {
  return loadUSGSSummary(daySummaryM4_5Url);
}
function loadDaySummaryM2_5() {
  return loadUSGSSummary(daySummaryM2_5Url);
}
function loadDaySummaryM1_0() {
  return loadUSGSSummary(daySummaryM1_0Url);
}
function loadDaySummaryAll() {
  return loadUSGSSummary(daySummaryAllUrl);
}
function loadWeekSummarySignificant() {
  return loadUSGSSummary(weekSummarySignificantUrl);
}
function loadWeekSummaryM4_5() {
  return loadUSGSSummary(weekSummaryM4_5Url);
}
function loadWeekSummaryM2_5() {
  return loadUSGSSummary(weekSummaryM2_5Url);
}
function loadWeekSummaryM1_0() {
  return loadUSGSSummary(weekSummaryM1_0Url);
}
function loadWeekSummaryAll() {
  return loadUSGSSummary(weekSummaryAllUrl);
}
function loadMonthSummarySignificant() {
  return loadUSGSSummary(monthSummarySignificantUrl);
}
function loadMonthSummaryM4_5() {
  return loadUSGSSummary(monthSummaryM4_5Url);
}
function loadMonthSummaryM2_5() {
  return loadUSGSSummary(monthSummaryM2_5Url);
}
function loadMonthSummaryM1_0() {
  return loadUSGSSummary(monthSummaryM1_0Url);
}
function loadMonthSummaryAll() {
  return loadUSGSSummary(monthSummaryAllUrl);
}
function loadMonthSignificant() {
  const now3 = DateTime.utc();
  const monthAgo = now3.minus({ month: 1 });
  return loadSignificant(monthAgo, now3);
}
function loadYearSignificant() {
  const now3 = DateTime.utc();
  const yearAgo = now3.minus({ years: 1 });
  return loadSignificant(yearAgo, now3);
}
function loadSignificant(start2, end) {
  return loadUSGSSummary(`${yearSignificant}&starttime=${start2.toISO()}&endtime=${end.toISO()}`);
}
function loadUSGSSummary(url2) {
  return loadUSGSGeoJsonSummary(url2).then((eventParameters) => {
    return eventParameters.eventList;
  });
}
function loadUSGSGeoJsonSummary(url2) {
  return loadRawUSGSGeoJsonSummary(url2).then((geojson) => {
    return parseGeoJSON(geojson);
  });
}
function loadRawUSGSGeoJsonSummary(url2) {
  const fetchInit = defaultFetchInitObj(JSON_MIME);
  return doFetchWithTimeout(url2, fetchInit, timeoutSec * 1e3).then((response) => {
    if (response.status !== 200) {
      return [];
    } else {
      return response.json();
    }
  }).then((jsonValue) => {
    if (isValidUSGSGeoJsonSummary(jsonValue)) {
      return jsonValue;
    } else {
      throw new TypeError(`Oops, we did not get roottype JSON!`);
    }
  });
}
function parseGeoJSON(geojson) {
  const quakeList = [];
  const description = geojson.metadata.title;
  for (const f of geojson.features) {
    const quake = parseFeatureAsQuake(f);
    quakeList.push(quake);
  }
  const out = new EventParameters();
  out.creationInfo = new CreationInfo();
  out.creationInfo.agencyURI = geojson.metadata.url;
  out.creationInfo.creationTime = DateTime.fromMillis(
    geojson.metadata.generated,
    UTC_OPTIONS
  );
  out.eventList = quakeList;
  out.description = description;
  return out;
}
function parseFeatureAsQuake(feature) {
  const quake = new Quake();
  quake.publicId = `quakeml:earthquake.usgs.gov/fdsnws/event/1/query?eventid=${feature.id}`;
  const p = feature.properties;
  if (p == null) {
    throw new Error("Geojson missing properties");
  }
  quake.eventId = stringify(feature.id);
  quake.descriptionList.push(new EventDescription(p.title));
  const origin = new Origin(
    DateTime.fromMillis(p.time, UTC_OPTIONS),
    feature.geometry.coordinates[1],
    feature.geometry.coordinates[0]
  );
  origin.depth = feature.geometry.coordinates[2] * 1e3;
  quake.originList.push(origin);
  const mag = p?.mag != null ? new Magnitude(p.mag) : ZERO_MAGNITUDE;
  mag.type = p.magType ? p.magType : ZERO_MAGNITUDE.type;
  quake.preferredOrigin = origin;
  quake.preferredMagnitude = mag;
  quake.magnitudeList.push(mag);
  return quake;
}
function isValidUSGSGeoJsonSummary(jsonValue) {
  if (!jsonValue || typeof jsonValue !== "object") {
    throw new TypeError("json is not object");
  }
  const jsonObj = jsonValue;
  if (!(typeof jsonObj.type === "string" && jsonObj.type === "FeatureCollection")) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, type should be FeatureCollection"
    );
  }
  if (!(typeof jsonObj.metadata === "object")) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, missing metadata"
    );
  }
  if (!Array.isArray(jsonObj.features)) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, features should be array"
    );
  } else {
    if (!jsonObj.features.every(isValidUSGSGeoJsonQuake)) {
      throw new TypeError(
        "geojson is not valid for USGS GeoJson, feature should be USGSGeoJsonFeature"
      );
    }
  }
  return true;
}
function isValidUSGSGeoJsonQuake(jsonValue) {
  if (!jsonValue || typeof jsonValue !== "object") {
    throw new TypeError("json is not object");
  }
  const jsonObj = jsonValue;
  if (!(typeof jsonObj.type === "string" && jsonObj.type === "Feature")) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, type should be Feature"
    );
  }
  if (!(typeof jsonObj.properties === "object")) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, missing properties"
    );
  }
  if (!(typeof jsonObj.id === "string")) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, id should be string"
    );
  }
  return true;
}
function loadUSGSTectonicLayer(url2) {
  if (!url2) {
    url2 = USGS_TECTONIC_SUMMARY_URL;
  }
  const fetchInit = defaultFetchInitObj(JSON_MIME);
  return doFetchWithTimeout(url2, fetchInit, timeoutSec * 1e3).then((response) => {
    if (response.status !== 200) {
      return [];
    } else {
      return response.json();
    }
  }).then((jsonValue) => {
    if (isValidUSGSTectonicGeoJsonSummary(jsonValue)) {
      return jsonValue;
    } else {
      throw new TypeError(`Oops, we did not get roottype JSON!`);
    }
  });
}
function isValidUSGSTectonicGeoJsonSummary(jsonValue) {
  if (!jsonValue || typeof jsonValue !== "object") {
    throw new TypeError("json is not object");
  }
  const jsonObj = jsonValue;
  if (!jsonObj.tectonic || typeof jsonObj.tectonic !== "object") {
    throw new TypeError("json.tectonic is not object");
  }
  const tectonic = jsonObj.tectonic;
  if (!(typeof tectonic.type === "string" && tectonic.type === "FeatureCollection")) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, tectonic should be FeatureCollection"
    );
  }
  if (!(typeof jsonObj.metadata === "object")) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, missing metadata"
    );
  }
  if (!Array.isArray(tectonic.features)) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, features should be array"
    );
  } else {
    if (!tectonic.features.every(isValidUSGSTectonic)) {
      throw new TypeError(
        "geojson is not valid for USGS GeoJson, feature should be USGSTectonicGeoJsonFeature"
      );
    }
  }
  return true;
}
function isValidUSGSTectonic(jsonValue) {
  if (!jsonValue || typeof jsonValue !== "object") {
    throw new TypeError("json is not object");
  }
  const jsonObj = jsonValue;
  if (!(typeof jsonObj.type === "string" && jsonObj.type === "Feature")) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, type should be Feature"
    );
  }
  if (!(typeof jsonObj.properties === "object")) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, missing properties"
    );
  }
  if (!(typeof jsonObj.id === "string" || typeof jsonObj.id === "number")) {
    throw new TypeError(
      "geojson is not valid for USGS GeoJson, id should be string"
    );
  }
  return true;
}

// src/vector.mts
var vector_exports = {};
__export(vector_exports, {
  DtoR: () => DtoR,
  RotatedSeismograms: () => RotatedSeismograms,
  rotate: () => rotate,
  vectorMagnitude: () => vectorMagnitude
});
var DtoR = Math.PI / 180;
var RotatedSeismograms = class {
  constructor(radial, azimuthRadial, transverse, azimuthTransverse, rotation) {
    this.radial = radial;
    this.azimuthRadial = azimuthRadial;
    this.transverse = transverse;
    this.azimuthTransverse = azimuthTransverse;
    this.rotation = rotation;
  }
};
function rotate(seisA, azimuthA, seisB, azimuthB, azimuth) {
  if (seisA.segments.length !== seisB.segments.length) {
    throw new Error(
      `Seismograms do not have same number of segments: ${seisA.segments.length} !== ${seisB.segments.length}`
    );
  }
  const rotOutRad = [];
  const rotOutTrans = [];
  for (let i = 0; i < seisA.segments.length; i++) {
    const result = rotateSeismogramSegment(
      seisA.segments[i],
      azimuthA,
      seisB.segments[i],
      azimuthB,
      azimuth
    );
    rotOutRad.push(result.radial);
    rotOutTrans.push(result.transverse);
  }
  const out = new RotatedSeismograms(
    new Seismogram(rotOutRad),
    azimuth % 360,
    new Seismogram(rotOutTrans),
    (azimuth + 90) % 360,
    azimuth - azimuthA
  );
  return out;
}
function rotateSeismogramSegment(seisA, azimuthA, seisB, azimuthB, azimuth) {
  if (seisA.y.length !== seisB.y.length) {
    throw new Error(
      `seisA and seisB should be of same lenght but was ${seisA.y.length} ${seisB.y.length}`
    );
  }
  if (!seisA.startTime.equals(seisB.startTime)) {
    throw new Error(
      `Expect startTime to be same, but was ${seisA.startTime.toISO()} ${seisB.startTime.toISO()}`
    );
  }
  if (seisA.sampleRate !== seisB.sampleRate) {
    throw new Error(
      `Expect sampleRate to be same, but was ${seisA.sampleRate} ${seisB.sampleRate}`
    );
  }
  if ((azimuthA + 90) % 360 !== azimuthB % 360) {
    throw new Error(
      `Expect azimuthB to be azimuthA + 90, but was ${azimuthA} ${azimuthB}`
    );
  }
  const rotRadian = 1 * DtoR * (azimuth - azimuthA);
  const cosTheta = Math.cos(rotRadian);
  const sinTheta = Math.sin(rotRadian);
  const x2 = new Float32Array(seisA.y.length);
  const y2 = new Float32Array(seisA.y.length);
  for (let i = 0; i < seisA.y.length; i++) {
    x2[i] = cosTheta * seisB.yAtIndex(i) - sinTheta * seisA.yAtIndex(i);
    y2[i] = sinTheta * seisB.yAtIndex(i) + cosTheta * seisA.yAtIndex(i);
  }
  const outSeisRad = seisA.cloneWithNewData(y2);
  const outSeisTan = seisA.cloneWithNewData(x2);
  if (seisA.sourceId) {
    outSeisRad.sourceId = seisA.sourceId.clone();
    outSeisRad.sourceId.subsourceCode = "R";
    outSeisTan.sourceId = seisA.sourceId.clone();
    outSeisTan.sourceId.subsourceCode = "T";
  }
  const out = {
    radial: outSeisRad,
    transverse: outSeisTan,
    azimuthRadial: azimuth % 360,
    azimuthTransverse: (azimuth + 90) % 360
  };
  return out;
}
function vectorMagnitude(seisA, seisB, seisC, orientCode) {
  if (seisA.segments.length !== seisB.segments.length || seisA.segments.length !== seisC.segments.length) {
    throw new Error(
      `Seismograms do not have same number of segments: ${seisA.segments.length}  !== ${seisB.segments.length}  !== ${seisC.segments.length}`
    );
  }
  const outData = [];
  for (let i = 0; i < seisA.segments.length; i++) {
    const result = vectorMagnitudeSegment(
      seisA.segments[i],
      seisB.segments[i],
      seisC.segments[i],
      orientCode
    );
    outData.push(result);
  }
  const outSeis = new Seismogram(outData);
  return outSeis;
}
function vectorMagnitudeSegment(seisA, seisB, seisC, orientCode) {
  if (seisA.y.length !== seisB.y.length || seisA.y.length !== seisC.y.length) {
    throw new Error(
      `seis should be of same length but was ${seisA.y.length} ${seisB.y.length} ${seisC.y.length}`
    );
  }
  if (seisA.sampleRate !== seisB.sampleRate || seisA.sampleRate !== seisC.sampleRate) {
    throw new Error(
      `Expect sampleRate to be same, but was ${seisA.sampleRate} ${seisB.sampleRate} ${seisC.sampleRate}`
    );
  }
  let y2;
  if (seisA.y instanceof Float64Array) {
    y2 = new Float64Array(seisA.y.length);
  } else {
    y2 = new Float32Array(seisA.y.length);
  }
  for (let i = 0; i < seisA.y.length; i++) {
    y2[i] = Math.sqrt(
      seisA.y[i] * seisA.y[i] + seisB.y[i] * seisB.y[i] + seisC.y[i] * seisC.y[i]
    );
  }
  const outSeis = seisA.cloneWithNewData(y2);
  if (!isDef(orientCode)) {
    orientCode = "M";
  }
  outSeis.sourceId = seisA.sourceId.clone();
  outSeis.sourceId.subsourceCode = orientCode;
  return outSeis;
}

// src/index.mts
var OregonDSP2 = __toESM(require_oregondsp(), 1);
var leaflet = __toESM(require_leaflet_src(), 1);
export {
  OregonDSP2 as OregonDSP,
  animatedseismograph_exports as animatedseismograph,
  axisutil_exports as axisutil,
  components_exports as components,
  cssutil_exports as cssutil,
  datalink_exports as datalink,
  dataset_exports as dataset,
  datechooser_exports as datechooser,
  distaz_exports as distaz,
  fdsnavailability_exports as fdsnavailability,
  fdsncommon_exports as fdsncommon,
  fdsndatacenters_exports as fdsndatacenters,
  fdsndataselect_exports as fdsndataselect,
  fdsnevent_exports as fdsnevent,
  fdsneventcomponent_exports as fdsneventcomponent,
  fdsnsourceid_exports as fdsnsourceid,
  fdsnstation_exports as fdsnstation,
  fdsnstationcomponent_exports as fdsnstationcomponent,
  fft_exports as fft,
  filter_exports as filter,
  handlebarshelpers_exports as handlebarshelpers,
  helicorder_exports as helicorder,
  infotable_exports as infotable,
  leaflet,
  leafletutil_exports as leafletutil,
  luxon_exports as luxon,
  miniseed_exports as miniseed,
  mseed3_exports as mseed3,
  mseed3eh_exports as mseed3eh,
  mseedarchive_exports as mseedarchive,
  nws_exports as nws,
  oregondsputil_exports as oregondsputil,
  organizeddisplay_exports as organizeddisplay,
  particlemotion_exports as particlemotion,
  quakeml_exports as quakeml,
  ringserverweb_exports as ringserverweb,
  ringserverweb4_exports as ringserverweb4,
  sacpolezero_exports as sacPoleZero,
  scale_exports as scale,
  seedcodec_exports as seedcodec,
  seedlink_exports as seedlink,
  seedlink4_exports as seedlink4,
  seismogram_exports as seismogram,
  seismogramloader_exports as seismogramloader,
  seismogramsegment_exports as seismogramsegment,
  seismograph_exports as seismograph,
  seismographconfig_exports as seismographconfig,
  seismographconfigeditor_exports as seismographconfigeditor,
  seismographmarker_exports as seismographmarker,
  seismographutil_exports as seismographutil,
  sorting_exports as sorting,
  spectraplot_exports as spectraplot,
  spelement_exports as spelement,
  stationxml_exports as stationxml,
  syngine_exports as syngine,
  taper_exports as taper,
  taup3_exports as taup3,
  transfer_exports as transfer,
  transition_exports as transition,
  traveltime_exports as traveltime,
  usgsgeojson_exports as usgsgeojson,
  util_exports as util,
  vector_exports as vector,
  version
};
/*! Bundled license information:

leaflet/dist/leaflet-src.js:
  (* @preserve
   * Leaflet 1.9.4, a JS library for interactive maps. https://leafletjs.com
   * (c) 2010-2023 Vladimir Agafonkin, (c) 2010-2011 CloudMade
   *)

jszip/dist/jszip.min.js:
  (*!
  
  JSZip v3.10.1 - A JavaScript class for generating and reading zip files
  <http://stuartk.com/jszip>
  
  (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
  Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
  
  JSZip uses the library pako released under the MIT license :
  https://github.com/nodeca/pako/blob/main/LICENSE
  *)
*/
